DEV Community

Cover image for Conditional Rendering
Ben Limpic
Ben Limpic

Posted on

Conditional Rendering

Conditional Rendering In React:

What is conditional rendering?

Conditional rendering is how we create dedicated components that fulfill specific tasks by implementing the ability to render or not render components based on their state and user input. Fortunately, we don’t have to worry about learning new functionality regarding conditional rendering in React, as it functions in the same way as vanilla Javascript. An example of conditional rendering could be…

Ex Use Case:
Imagine a big red button. Every time we click the button, we want to know if the button has been clicked an even or odd amount of times. If the button click is even, we want the button to turn blue. If the return is odd, we want the button to turn yellow.

Here is an example of using conditional rendering in-line. One of the cool things about conditional rendering is if you create a statement using an && logical operator, a falsey result will return the first part of the statement while ignoring everything after the &&. This method is relatively unique and clever, in my opinion. Below is an illustration of this method from React Documentation.

React Docs Ex 1.

render() {
  const count = 0;
  return (
    <div>
      {count && <h1>Messages: {count}</h1>}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Another interesting use case for in-line conditional rendering is the if/else ternary statement; this may be the most useful conditional statement in React. As we can imagine, we have a condition to evaluate. The conditional is found to be true, return true, and if false, return false. Again, the amount of code used and the resulting functionality is a high ratio of usefulness to lines of code.

React Docs Ex 2.

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Condition ? True : false

We can do a whole lot with this little statement.

Top comments (0)