DEV Community

Cover image for How to conditionally render components in React
Luqman Shaban
Luqman Shaban

Posted on

How to conditionally render components in React

I've been working on a messaging web app this week and one of the features I wanted to implement was conditionally rendering multiple components when a particular condition is met. Let me explain.

Imagine a restaurant menu page that has a variety of food items in different categories, ranging from regular meals to drinks and desserts. You might want to add filters to render a specific category like desserts. There are several ways to achieve this, here are a few:

  • Using a bunch of if/else statements;
  • Using a ternary operator
  • Exclusive component rendering

We'll implement the third option while sing our restaurant menu page example, lets create three components returning the menu items:



const AllFoodItems = () => <div>All Menus</div>
const MealsComponent = () => <div>Meals</div>
const DessertComponent = () => <div>Dessert</div>
const DrinksComponent = () => <div>Drinks</div>



Enter fullscreen mode Exit fullscreen mode

This is just a simple use case, but it will do the job. Suppose we wanted to exclusively render the desserts when the user clicks on the desserts button. We can do this by creating an array of boolean values, with each value representing a component, e.g., element 1 of the array, will represent AllFoodItems and element 2 represents MealsComponent and so on.

Initially, we set all the values to false except for the first one, which will be the default component rendered.



const [renderedComponents, setRenederedComponent] = useState([true, false, false, false])


Enter fullscreen mode Exit fullscreen mode

The next step would be to create a function that will update the indexes by setting all their values to false except for one.



const toggleComponent = (index: number) => setRenederedComponent(prev => prev.map((_, i) => i === index))


Enter fullscreen mode Exit fullscreen mode

In the function above, we're passing an argument index, and then mapping over the renderedComponents array. When we reach the element whose index matches the number passed in the argument, we update its value to true, while setting the other elements to false.

In the following step, we call this function inside button elements and pass the corresponding index for the component. You could imagine this as your filter component that renders a specific component on a click event:



    <ul>
        <li>
          <button onClick={() => toggleComponent(0)}>All</button>
        </li>
        <li>
          <button onClick={() => toggleComponent(1)}>Meals</button>
        </li>
        <li>
          <button onClick={() => toggleComponent(2)}>Dessert</button>
        </li>
        <li>
          <button onClick={() => toggleComponent(3)}>Drinks</button>
        </li>
      </ul>


Enter fullscreen mode Exit fullscreen mode

Finally, we conditionally render the components when they're truthy:



      <div>
        {renderedComponents[0] && <AllFoodItems />}
        {renderedComponents[1] && <MealsComponent />}
        {renderedComponents[2] && <DessertComponent />}
        {renderedComponents[3] && <DrinksComponent />}
      </div>


Enter fullscreen mode Exit fullscreen mode

Here's the full code:



import { useState } from 'react'


const AllFoodItems = () => <div>All Menus</div>
const MealsComponent = () => <div>Meals</div>
const DessertComponent = () => <div>Dessert</div>
const DrinksComponent = () => <div>Drinks</div>


const App = () => {
  const [renderedComponents, setRenederedComponent] = useState([true, false, false, false])

  const toggleComponent = (index: number) => setRenederedComponent(prev => prev.map((_, i) => i === index))
  return (
    <div>
      <ul>
        <li>
          <button onClick={() => toggleComponent(0)}>All</button>
        </li>
        <li>
          <button onClick={() => toggleComponent(1)}>Meals</button>
        </li>
        <li>
          <button onClick={() => toggleComponent(2)}>Dessert</button>
        </li>
        <li>
          <button onClick={() => toggleComponent(3)}>Drinks</button>
        </li>
      </ul>

      <div>
        {renderedComponents[0] && <AllFoodItems />}
        {renderedComponents[1] && <MealsComponent />}
        {renderedComponents[2] && <DessertComponent />}
        {renderedComponents[3] && <DrinksComponent />}
      </div>
    </div>
  )
}

export default App


Enter fullscreen mode Exit fullscreen mode

Live demo:

Demonstration gif

This is a simple demonstration of how you can conditionally render components in React. It's a better approach when dealing with scenarios like food menus, product categories, etc.

I hope this was helpful, Lol!

Do you know a better way to do this?

Let's connect

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.