DEV Community

Aakash Srivastav
Aakash Srivastav

Posted on

Conditional Rendering in React

What is conditional rendering in React?

Conditional rendering as a term describes the ability to render different UI markup based on certain conditions. In other words, it is a way to render different elements or components based on a condition.

Scenarios where you will mostly use conditional rendering:

  • Rendering external data from an API
  • Showing/hiding elements
  • Toggling application functionality
  • Implementing permission levels
  • Authentication and Authorization

When we are developing a React application, we often need to show or hide an element given a certain condition. Be it a user interaction, the presence of data coming from a request, or even permission levels.In a conditional render a component decides based on one or several conditions which elements it will return. For instance, it can either return a list of items or a message that says "Loading...". When a component has conditional rendering, the instance of the rendered component can have different looks.

1. Using if/else:

The easiest way to have a conditional rendering is to use an if else in React in your render method. Imagine you don't want to render your component, because it doesn't have the necessary props or data. For instance, an App component shouldn't render the name and date until it's loading. You can use an if statement to return true if it's loading.

Example 1 -

.
.
function isLoading(){
  return true
}

export default class App extends React.Component{
  render(){
    if ( isLoading() === true ) {
      return null
    }

    const name = 'Aakash'

    return (
      <div>
        <h1>Hello, {name}</h1>
        <p>Today is {new Data().toLocaleString()}</p>
      </div>
    );
  }
}
.
.

Now , we'll get empty page because we're telling React - Don't show any UI if isLoading is true

2. Using ternary orperator:

JavaScript’s ternary operator is a little like a shorthand if/else statement, but with one crucial difference: it’s an expression, not a statement.

Example 2 -

ifTrue ? thenA : elseB
 <div>
    {props.question ? <h3>Question: {props.question}</h3> : null}
</div>

OR

Example 3 -

 <div>
     <h3 style={{display: props.question ? "block" : "none"}}>Question:{props.question}</h3>
     <h3>Answer: {props.punchLine}</h3>
     <hr/>
</div>

3. Using AND orperator:

JavaScript’s makes the && operator more useful than it might look at first.

The logical && helps us specify that an action should be taken only on one condition, otherwise, it would be ignored entirely. In other words , If the condition is true, the expression after the logical && operator will be the output. If the condition is false, React ignores and skips the expression.
This is useful for situations where you only need to take an action when a certain condition is true, otherwise do nothing.

Example 4 -

<div>
    {props.question && <h3>Question: {props.question}</h3>}

    <h3>Answer: {props.punchLine}</h3>
</div>

Example 5 -

<div>
    <h3 style={{display: !props.question && "none"}}>Question: {props.question} 
    </h3>
    <h3>Answer: {props.punchLine}</h3>
    <hr/>
</div>
  • The 2nd and 4th example mentioned above will do the same thing i,e they will check whether there is any "question" property present or not , if "yes" , it will be rendered , otherwise "null" will be returned.
  • In example 3rd and 5th , they will check whether "question" property is present or not , if not then it will apply the CSS rule of "display:none" otherwise "display:block".

Conclusion

Just as with many things in programming, there are many ways to implement conditional rendering in React.

All of the above approaches are valid when used in the right context, it is up to us to choose the appropriate method in appropriate situation.

I’d say that with exception of the method (if/else with many returns), you’re free to choose whatever method you want.

You can decide which one is best for your situation based on:

Your programming style
How complex the conditional logic is
How comfortable you are with JavaScript, JSX, and advanced React concepts (like HOCs)
And all things being equal, always favor simplicity and readability.

And you, do you use any specific approach you would like to share with me?

Happy coding!

If you have any question regarding this or anything I should add, correct or remove, feel free to comment, email or DM me. Thanks !!!

Top comments (2)

Collapse
 
dmcshehan profile image
Shehan Disanayake

An informative article. Keep up the good work!

Collapse
 
aakashsr profile image
Aakash Srivastav

Thanks 😊