A Clean Way to Conditionally Render Components
Anxiny
Posted on January 16, 2022
Today, I want to share a clean way to conditionally render child components while using React. It's very simple.
Live Demo:
https://codesandbox.io/s/if-component-demo-9iipl?file=/src/App.js
Before
function App(){
// ...
return <div>
{someCondition?
<SomeChildA>
<div>Some Contents</div>
<div>Some Contents</div>
<div>Some Contents</div>
</SomeChildA>
:
<SomeChildB>
<div>Some Contents</div>
<div>Some Contents</div>
<div>Some Contents</div>
</SomeChildB>}
</div>
}
After
function App(){
// ...
return <div>
<If condition={someCondition}>
<SomeChildA>
<div>Some Contents</div>
<div>Some Contents</div>
<div>Some Contents</div>
</SomeChildA>
</If>
<If condition={!someCondition}>
<SomeChildB>
<div>Some Contents</div>
<div>Some Contents</div>
<If condition={someOtherCondition}>
<NestExample/>
</If>
<div>Some Contents</div>
</SomeChildB>
</If>
</div>
}
<If/> Component
function If(props) {
return props.condition ? <>{props.children}</> : null;
}
Thanks for reading! Have a nice day!
💖 💪 🙅 🚩
Anxiny
Posted on January 16, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.