Sometimes we want to check if the right data has been loaded into the props, the state or the context before rendering our React.js components. In the meanwhile, we usually show a loading indicator.
React Only If is a higher order component that simplifies the process and makes it more declarative.
Before:
const UserContainer = props => {
if (!props.user) {
return <Spinner />;
}
return <User user={props.user} />;
};
After:
const UserContainer = props => <User user={props.user} />;
const UserContainerOnlyIf = onlyIf(props => props.user, Spinner)(UserContainer);
$ npm install react-only-if --save
<script src="https://unpkg.com/react-only-if/umd/only-if.min.js"></script>
Parameter | Type | Description |
---|---|---|
condition | func | The condition function. It receives props, context and state. |
Placeholder | element | (optional) The component to render when the condition is false. |
Following a discussion in #2, the library has been recently rewritten (thanks Frederik).
The version 1.x introduces some breaking changes in order to enforce consistency for stateless functional components and to make the library play nicely when using functional composition on multiple higher order components.
// v0.x
const ComponentOnlyIf = onlyIf(Component, (props, state, context) => {...}, Placeholder);
// v1.x
const ComponentOnlyIf = onlyIf((props, context, state) => {...}, Placeholder)(Component);
$ npm test