/c-when

<When/> - conditionally render a React component

Primary LanguageJavaScript

<When/>

Greenkeeper badge

Travis npm package Coveralls

Use case

Instead of using inline JavaScript to check a condition

const App = ({isLoggedIn}) => (
  <div>
    {(isLoggedIn)?(
      <div>Some secret content here</div>
    ):(null)}
  </div>
);

you can use <When/> to conditionally render some React

import When from 'c-when';

const App = ({isLoggedIn}) => (
  <div>
    <When predicate={isLoggedIn}>
      <div>Some secret content</div>
    </When>
  </div>
);

you can also pass a function as the child of <When/>. The function should not need any parameters and should return the children you'd like rendered when predicate is true. Passing in a function is useful when the children need to access objects that are only available if the predicate is true.

import When from 'c-when';

const App = ({user}) => (
  <div>
    <When predicate={user !== undefined}>
    {() => (
      <div>Welcome back {user.name}!</div>
    )}
    </When>
  </div>
);

If you'd rather pass in a render prop, you can do that instead.

import When from 'c-when';

const App = ({user}) => (
  <div>
    <When
      predicate={user !== undefined}
      render={() => (
        <div>Welcome back {user.name}!</div>
      )}
    />
  </div>
);