An Interest In:
Web News this Week
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
- March 14, 2024
November 7, 2022 09:43 am GMT
Original Link: https://dev.to/rubenarushanyan/react-comfort-conditional-rendering-in-react-become-easier-and-cleaner-31mc
React Comfort - conditional rendering in react become easier and cleaner.
You can find the full documentation on the website
If
, Else
, and ElseIf
is a react helper components with the help of which conditional rendering in react become easier and cleaner.
Installation
npm install react-comfort
Examples
Simple example using If
and Else
combination.
import {If, Else} from 'react-comfort'const Bar = (props) => { return ( <If condition={props.age >= 18}> <h2></h2> <p>Buy alcohol!</p> <Else> <h2></h2> <p>Sorry, children cannot purchase alcohol!</p> </Else> </If> )}
More complex example using If
, Else
, and ElseIf
combination.
import {If, Else, ElseIf} from 'react-comfort'const App = (props) => { return ( <If condition={props.condition_1}> <p>Show, if cond_1 is true</p> <Else> <p>Show, if condition_1 is false</p> </Else> <ElseIf condition={props.condition_2}> <p>Show, if condition_1 is false and condition_2 is true</p> </ElseIf> <ElseIf condition={props.condition_3}> <p>Show, if condition_1 is false and condition_3 is true</p> </ElseIf> </If> )}
Example for nested If
-Else
combination.
<If condition={condition_1}> <Else condition={condition_2}> <If condition={condition_3}> <Else condition={condition_4}> Hello! </Else> </If> </Else></If>
Function Children
Regardless of the condition, both the children of If
and Else
will be executed by JavaScript This can lead to unwanted side effects and performance issues. In such cases, we can pass a function instead of children.
Let's consider the following example:
<If condition={hasResult}> <p>Result: { getResult() }</p> <Else> <p>No Result</p> </Else></If>
In the example above, the getResult()
function will always be called regardless of whether hasResult
is true or false.
Let's solve that problem
<If condition={hasResult}> {() => <p>Result: { getResult() }</p>} <Else> <p>No Result</p> </Else></If>
Links
Original Link: https://dev.to/rubenarushanyan/react-comfort-conditional-rendering-in-react-become-easier-and-cleaner-31mc
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To