A React component that lets you do conditional rendering, declaratively.
npm install --save react-logic-switch
import { Switch, Case, Default } from 'react-logic-switch';
function MySwitchComponent({ isNightTime }) {
return (
<Switch arg={isNightTime}>
<Case match={true}>
<DarkModePage />
</Case>
<Default>
<LightModePage />
</Default>
</Switch>
);
}
react-logic-switch
exports three React components: Switch
, Case
and Default
. Any meaningful usage will require all 3 components.
Switch
is the top-level React component. It only accepts Case
components, and exactly one Default
component, as children. It also takes an arg
prop, which can be used to decide which Case
to render.
The Case
component takes exactly one of either the test
or match
prop. These are used by the Switch
parent to decide which component to render.
-
match
- If you pass amatch
prop, the parentSwitch
will render if it's the firstCase
component with a match value equal to the parentSwitch
component'sarg
prop. -
test
- If you pass a function as atest
prop, the parentSwitch
will call the function and use the output to decide whether to render the switch.
<Switch arg={friends}>
<Case test={friends => friends.length > 3}>
Chat with your friends!
</Case>
<Default>
Connect with your friends!
</Default>
</Switch>
If a Switch
receives more than one matching Case
, only the first one will be rendered.
The Switch
component will render the contents of the Default
component if no Case
children match.
Copyright 2020 Elsevier