DEV Community

Cover image for React Comfort - conditional rendering in react become easier and cleaner.
Ruben Arushanyan
Ruben Arushanyan

Posted on • Updated on

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

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

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

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

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>
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

Links

Top comments (18)

Collapse
 
brentdalling profile image
Brent Dalling

I can see this being slightly easier to read. Is there anyway to convert this to an attribute to control it like VUE? But, as @zirkelc mentioned, why use this compared to the native JSX ternary? Using this package adds potential resource bloat and technical debt to the project.

I think you did a nice job. Congrats on your package!

Collapse
 
rubenarushanyan profile image
Ruben Arushanyan

@brentdalling Thanks for the question. Please see dev.to/rubenarushanyan/comment/22mg8

Collapse
 
gitfudge profile image
gitfudge

Though the package you've written is certainly cool, I agree with @brentdalling about the tech debt. Instead of including an additional package that allows conditional rendering, I'd rather use something like

const Component = () => {
  const [index, setIndex] = useState(0);
  const [value, setValue] = useState("");

  const renderContent = () => {
    switch (index) {
      case 0:
        return <Component1 />
      case 1:
        return <Component2 />
      // More cases
    }
  }

  const renderConditionalContent = () => {
    if (value === "One") return <CondComp1 />
    if (value === "Two") return <CondComp2 />
    if (value === "Three") return <CondComp3 />
    if (value === "Four") return <CondComp4 />
    return <DefaultComp />
  }

  return (
    <>
      { renderContent() }
      { renderConditionalContent() }
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
rubenarushanyan profile image
Ruben Arushanyan

@dbigpot You're right, we can do it your way. But I prefer to use If, Else because it is more readable and clear.

Thread Thread
 
brentdalling profile image
Brent Dalling

@rubenarushanyan I want to be clear. This package seems useful. You did a great job! Thank you for your community contribution.

Senior developers / engineers are typically more hesitant to use packages like this. They are not likely to be maintained for sustained periods of time and increase the burden of technical debt. Especially if they want to upgrade other dependencies that may break your package.

Technical debt is a real concern. When I'm working on a clients code base I have to make very careful decisions on which packages I add. I have to be absolutely certain that the long term benefit is greater than the short term benefit. For example, this may help me right now. But, as the React framework itself grows, will this be outdated soon? Will the package receive new framework version support? Will the package receive security support? These questions are questions that I ask before considering a package. Therefore, in situations like this, I usually default to the frameworks native behavior or use a vanilla JS solution.

I can see this being a better developer experience for newer developers or smaller projects where comparability and long term support are not required.

I really think you did a great job. I would consider this package as it matures to simplify and improve my developer experience. This is terrific. Thanks!

Thread Thread
 
brentdalling profile image
Brent Dalling

@dbigpot Your solution is how I usually do component switching/toggling. I believe this is also how most tutorials/books/manuals refer to this. I like it. It is simple and easy to read. There's no "magic" here. Thanks!

Thread Thread
 
rubenarushanyan profile image
Ruben Arushanyan

@brentdalling Thanks. I agree with you absolutely

Collapse
 
matin192hp profile image
matin HP • Edited

this is awesome

Collapse
 
rubenarushanyan profile image
Ruben Arushanyan

@matin192hp Thanks

Collapse
 
guscarpim profile image
Gustavo Scarpim

NIce

Collapse
 
rubenarushanyan profile image
Ruben Arushanyan

@guscarpim Thanks

Collapse
 
samomelkonyan profile image
SamoMelkonyan

Cool !!!

Collapse
 
zirkelc profile image
Chris Cook

What is the advantage over plain JSX syntax with tenary operator?

{props.condition_1 ? () : ()}

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.