Switch
The Switch
component can be used for complex conditional rendering. The component can be switch by multiple "cases"
of components and an "default"
component to render in case the given dynamic value does not match any case.
Render dynamic components cleanly using this component.
Import
import { Switch } from 'react-haiku';
Usage
🚀
import { useState } from 'react';
import { Switch } from 'react-haiku';
const reactions = {
'LIKE': 'like',
'FIRE': 'fire',
'LOVE': 'love'
}
const CaseReactionLike = () => <h1>👍</h1>
const CaseReactionFire = () => <h1>🔥</h1>
const CaseReactionLove = () => <h1>❤️</h1>
const CaseDefault = () => <h1>🚀</h1>
export const Component = () => {
const [reaction, setReaction] = useState();
const handleReact = (e) => {
const reactionSelected = e.target.value;
setReaction({
[reactions.LIKE]: reactions.LIKE,
[reactions.FIRE]: reactions.FIRE,
[reactions.LOVE]: reactions.LOVE
}[reactionSelected]);
}
return (
<>
<select value={reaction} onChange={handleReact}>
<option value={'default'}>Default</option>
<option value={reactions.LIKE}>👍 Like</option>
<option value={reactions.FIRE}>🔥 Fire</option>
<option value={reactions.LOVE}>❤️ Love</option>
</select>
<Switch
value={reaction}
components={{
[reactions.LIKE]: CaseReactionLike,
[reactions.FIRE]: CaseReactionFire,
[reactions.LOVE]: CaseReactionLove,
}}
defaultComponent={CaseDefault}
/>
</>
)
};
API
The Switch
component accepts the following props:
value
- the value to check with the cases to render the corresponding component.components
- the list of case components to be rendered when case matches.defaultComponent
- the "default" component to be rendered if the value does not match any of the given cases.