1.0.0 • Published 8 years ago

react-only-if v1.0.0

Weekly downloads
5
License
MIT
Repository
github
Last release
8 years ago

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

ParameterTypeDescription
conditionfuncThe condition function. It receives props, context and state.
Placeholderelement(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