DEV Community

Discussion on: React Comfort - conditional rendering in react become easier and cleaner.

Collapse
 
rubenarushanyan profile image
Ruben Arushanyan • Edited

@zirkelc Thanks for the question.

In practice everything is more complicated than the simple example you mentioned.

{props.condition_1 ? (props.condition_2 ? () : ()) : (props.condition_3 ? () : ())}

import {If, Else, ElseIf} from 'react-comfort'

<If condition={props.condition_1}>
     <If condition={props.condition_2}>
       ...
         <Else>
            ...
         </Else>
     </If>
    <ElseIf condition={props.condition_3}>
        ...
        <Else>
           ...
        </Else>
    </ElseIf>
</If>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
zirkelc profile image
Chris Cook

I see your point and agree that tenary expression can get quite complicated with multiple conditions.

In your example, I would create two separate if statements for condition_2 and condition_3 and include the first condition_1 in both cases:

{props.condition_1 && props.condition_2 ? <div>...</div> : <div>...</div>}
{props.condition_1 && props.condition_3 ? <div>...</div> : <div>...</div>}
Enter fullscreen mode Exit fullscreen mode

I would argue that evaluating the condition_1 condition twice is still way more efficient than the overhead produced by unnecessary React nodes for If, ElseIf, Else. All these components will be translated to React.createElement(component, props, ...children) calls.

Thread Thread
 
rubenarushanyan profile image
Ruben Arushanyan

@zirkelc You are right please see the solution:

react-comfort.js.org/docs/componen...

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
zirkelc profile image
Chris Cook

But why make it more complicated than it has to be?


{hasResult ? <p>Result: { getResult() }</p> : <p>No Result</p>}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
rubenarushanyan profile image
Ruben Arushanyan

@zirkelc to make it more readable ) We can also don't use JSX, but we use it to make code more readable and comfortable.