react-maybe v1.1.4
react-maybe
Render one of two React components
react-maybe is built behind a monad which conditionally displays one of two components based on the
value contained in the of prop. If the value is one of null, undefined or false, the
orElse component will be displayed. In all other cases the component passed to the either prop
will be displayed.
The value in the of prop can be altered through the use map prop. The map prop could be a
function or an array of functions. The value of of will be passed to the first map function,
each additional map function will receive the return value of the previous one in the array. The
return value of the last map funtion will then be used to determine which component to render.
Installation
Installation is currently available via npm:
$ npm i -S react-maybeUsage
Basic
A basic react-maybe implementation will display one of two components based on the value of the
of prop:
import Maybe from 'react-maybe';
const Component = ({ showChevronUp }) => (
<div>
<Maybe of={showChevronUp} either={<ChevronUp />} orElse={<ChevronDown />} />
</div>
);Advanced
A more advanced react-maybe implementation can alter the value of the of prop through use of
the map prop:
import Maybe from 'react-maybe';
const sampleUser = { name: 'Maybe', isActive: false };
const isActive = user => user.isActive;
const Component = () => (
<div>
<Maybe of={sampleUser} map={isActive} either={<ActiveUser />} orElse={<InactiveUser />} />
</div>
);The above will render the orElse as our sample user is inactive
or
import Maybe from 'react-maybe';
const sampleUser = { name: 'Maybe', isActive: true };
const isActive = user => (user.isActive ? user : false);
const hasPhoneNumber = user => !!user.phone;
const Component = () => (
<div>
<Maybe
of={sampleUser}
map={[isActive, hasPhoneNumber]}
either={<ActiveUserWithPhone />}
orElse={<UserWithoutPhone />}
/>
</div>
);The above example will render the orElse component as our user is active, but has no phone
number
Properties
of
The value that the monad will contain.
map
Accepts a function or an array of functions which has the ability to transform the value contained in the
ofprop.either
Accepts a component that will be rendered in all cases where the value of the
ofprop is not equal toundefined,null, orfalse.orElse
Accepts a component that will be rendered when the value of the
ofprop is equal toundefined,null, orfalse.
Running tests
You can either run the tests with npm or docker.
NPM
$ npm i
$ npm testDocker
$ docker-compose run --rm app npm i
$ docker-compose up