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 amatchprop, the parentSwitchwill render if it's the firstCasecomponent with a match value equal to the parentSwitchcomponent'sargprop. -
test- If you pass a function as atestprop, the parentSwitchwill 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
