Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 7, 2022 09:43 am GMT

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:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To