react-only-if

1.0.0 • Public • Published

Build Status

React Only If

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);

Installation

Npm

$ npm install react-only-if --save

Umd

<script src="https://npmcdn.com/react-only-if/umd/only-if.min.js"></script>

API

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.

Note for version 0.x users

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);

Test

$ npm test

Readme

Keywords

Package Sidebar

Install

npm i react-only-if

Weekly Downloads

1

Version

1.0.0

License

MIT

Last publish

Collaborators

  • michelebertoli