react-if-lite
v0.1.0
Published
Lightweight conditional rendering for React (If, Unless, Switch/Case/Default).
Downloads
207
Readme
react-if-lite
Lightweight conditional rendering for React. Declarative <If>, <Unless>, and <Switch> components with optional <Then> / <Else> and <Case> / <Default> children. By default no wrapper element is rendered.
Install
npm install react-if-lite
# or
pnpm add react-if-lite
# or
yarn add react-if-liteUsage
import { Case, Default, Else, If, Switch, Then, Unless } from 'react-if-lite'If / Then / Else
Turn a ternary into a more readable block:
function Bar({ name, age, drinkingAge }) {
return (
<div>
<If cond={age >= drinkingAge}>
<Then>
<span className="ok">
Have a beer,
{name}
!
</span>
</Then>
<Else>
<span className="not-ok">
Sorry,
{name}
, you are not old enough.
</span>
</Else>
</If>
</div>
)
}Shorthand with props (no <Then> / <Else> children):
<If cond={isLoggedIn} then={<Profile />} else={<Login />} />Unless
Renders children when the condition is false:
<Unless cond={isLoading}>
<Then>
<span>Content is ready</span>
</Then>
<Else>
<span>Loading...</span>
</Else>
</Unless>Or shorthand:
<Unless cond={hasError}>No error</Unless>Switch / Case / Default
Render the first matching <Case>, or <Default> if none match:
function Example() {
const myNumber = 3
return (
<div>
<Switch>
<Case cond={myNumber === 9}>Nine</Case>
<Case cond={myNumber > 1}>Greater than one</Case>
<Default>Fallback</Default>
</Switch>
</div>
)
}Value-based matching (first <Case> whose cond equals value):
<Switch value={status}>
<Case cond="loading">Loading...</Case>
<Case cond="error">Something went wrong</Case>
<Case cond="success">Done!</Case>
<Default>Unknown status</Default>
</Switch>Wrapping with as
By default there is no wrapper. Use as to wrap the chosen branch in an element or component; other props (e.g. className) are passed through.
<If as="div" className="card" cond={isActive}>
<Then><p>Active</p></Then>
<Else><p>Inactive</p></Else>
</If>
// Renders:
// <div class="card">
// <p>Active</p> or <p>Inactive</p>
// </div>With a custom component:
<If cond={!loading} as={AnimatePresence} initial={false}>
<Then
as={motion.div}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
>
{/* ... */}
</Then>
<Else
as={motion.div}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
>
{/* ... */}
</Else>
</If>
// AnimatePresence receives initial={false} and the chosen child as children