Conditional Rendering in React.js

Lorraine Nabua
3 min readMay 14, 2021

What is Conditional Rendering?

Conditional rendering a way to process delivering different elements and components based on certain conditions. In React, conditional rendering is the same way that conditions work in JavaScript. There are many ways to use conditional rendering. Depending on the problem you are trying to solve, some maybe more fitting than others. A few common methods are as follows:

  • if/else
  • Ternary operation
  • Inline IF with Logical && operator
  • Switch case operator

In this blog, we will be adding conditional rendering to the React App example from my previous blog, Build a Search Bar in React.js. We will be focusing on using the if/else statement and ternary operator. Below is the revised code to my React App as well as the FlowerForm component code.

Revised code:

In the code above, I included a view state with a value of “false” as well as a viewForm function and a cancel function. The viewForm and cancel functions changes the state of view as soon as they are triggered which then changes the appearance of the app. When the “Add New Flower” button is clicked, the viewForm function is triggered and the FlowerForm appears. When the “cancel” button in the FlowerForm component is clicked, the cancel function is triggered, the FlowerForm disappears, and the webpage returns to its original appearance.

FlowerForm component:

Demo:

If/else Statement

Below is how the code will look using an if/else statement. The if/else statement can be used in render() and should not be used inside a return statement and JSX. In order to keep everything in the same <div> or on the same webpage, the renderContent function was created to contain the if/else statement which can now be passed in the return statement in render().

Ternary Operator

The ternary operator is my most preferred way to do conditional rendering in React. Using the if/else statement can make it difficult to use Javascript in JSX. Therefore, the most suited way to do so is by using a ternary operator. As you can see below, we have greatly reduced the lines of code. We no longer need to create a function to store our conditional.

Resources:

--

--