react-ifs
This package provides a simple conditional logic wrapper for React components. It exports a function component, If
.
If
requires a condition
prop and either child elements or a then
prop. It accepts optional else
and unless
props. It returns a single, unmodified prop value based on the combination of props it has received.
The package is intended as a reusable drop-in to clean up repetitive conditional assignments in dynamic React applications.
Install
npm i react-ifs
or
yarn add react-ifs
Import
;
API
If/children
<If condition=true> <Foo /></If>
<Foo />
will be returned. If the condition
evaluates to false
, null
will be returned. If the condition evaluates to false, null
will be returned.
If/then
<If condition=true then=<Foo /> />
<Foo />
will be returned. As above, if the condition
evaluates to false
, null
will be returned.
then
overrides children
If/then + children → <If condition=true then=<Foo />> <Bar /></If>
<Foo />
will be returned.
If/else
<If condition=false then=<Foo /> else=<Bar /> />
<Bar />
will be returned.
If/else/unless
<If condition=false then=<Foo /> else=<Bar /> unless=<Baz /> />
<Baz />
will be returned if it evaluates to truthy.
Examples
Login
Either a login form or a logout button is displayed depending on the loggedIn
prop.
;; ;; const Login = <If condition=!propsloggedIn else=<LogoutButton />> <LoginForm /> </If>; ;
Access control
The content that renders depends on both subscribed
and promotional
props.
;; ;; const Page = { const trial = propspromotional ? <MemberContent /> : null; return <If condition=propssubscribed then=<MemberContent /> else=<Demo /> unless=trial /> ;}; ;
Other conditional displays
One menu renders depending on the time_of_day
prop.
;; ;;; const Menu = <> <If condition=propstime_of_day === 'morning' then=<BreakfastMenu /> /> <If condition=propstime_of_day === 'midday' then=<LunchMenu /> /> <If condition=propstime_of_day === 'evening' then=<DinnerMenu /> /> </>; ;