The react-context-switch package provides an easy-to-use and friendly way to conditionally render components in React.
Using the Switch, Case, and CaseElse components, you can cleanly handle different conditions avoiding messy conditionals.
You can see this as a technique wrapped in a component.
It is also possible to nest Switch components, allowing for even more powerful and flexible conditional rendering.
import Reactfrom"react";import{Switch,Case,CaseElse}from"react-context-switch";functionApp(){return(<divclassName="App"><headerclassName="App-header"><Switchvalue={newDate().getFullYear()}><Casewhen={2023}><p>2023</p></Case><Casewhen={[(x)=>x===2024]}><p>2024</p></Case><CaseElse><Switchvalue={~~(newDate().getFullYear()/100)}><Casewhen={20}><NearFutureComponent/></Case><Casewhen={(x)=>[21,22].includes(x)}><FutureComponent/></Case><CaseElse><DistantFutureComponent/></CaseElse></Switch></CaseElse></Switch></header></div>);}functionNearFutureComponent(){return<div>{"The Near Future is here!"}</div>;}functionFutureComponent(){return<div>{"The Future is here!"}</div>;}functionDistantFutureComponent(){return<div>{"The Distant Future is here!"}</div>;}exportdefaultApp;
Please find an example of a complex conditional render on codesandbox
I use this components extensively in my projects. I hope you’ll find them useful too.
This component was inspired from Mike Talbot‘s work. Thanks Mike!