Skip to main content

Command Palette

Search for a command to run...

Conditional Rendering and Rendering List in React

In this blog, We will be discussing Conditional Rendering, Logical And Operator, Ternary Operator, Rendering Lists and a lot more.

Updated
3 min read
Conditional Rendering and Rendering List in React
D

I am a Software Engineer with 3+ years of experience, currently at P360. I have a passion for creating intuitive web interfaces and actively contribute to tech communities as the Organizer of GDG Siliguri, ex-Microsoft Learn Student Ambassador, and former Hack Club Lead. As a tech speaker, I’ve presented at events like FrontendDays Siliguri, GDG Bhopal, and Azure DevDay. I’m also passionate about hackathons and open-source: Smart India Hackathon 2020 winner, HacktoberFest contributor, and mentor to the winning team of SIH 2022.

Introduction

Sometimes we want to show a React component when a condition yields true. It is called Conditional Rendering. Also, rendering through a list of values to display a Component multiple times is very common in React. In this blog, we are discussing these two topics.

Conditional Rendering in Action

In React, we can use any valid JavaScript code inside JSX. So, we can conditionally render a Component with these two operators in React:

  1. Using Logical And Operator (&&).

  2. Using Ternary Operator (?:).

1. Using Logical And Operator (&&):

Logical And Operator is used if you want to render a component only when a condition yields true. We can compare it with the if condition. But it can’t handle the else case. Below is a simple example of Logical And Operator:

import { useState } from 'react';

const App = () => {
  const [isActive, setIsActive] = useState(true);
  return (
      <div>
      <h1>Active User</h1>
      {
        isActive && <p>User is Active Now.....</p>
      }
    </div>
  )
}

export default App;

2. Using Ternary Operator (?:):

Ternary Operator is used if you want to render one component only when a condition yields true and another Component if yields false. Below is a simple example of a Ternary Operator:

import { useState } from 'react';

const App = () => {
  const [isActive, setIsActive] = useState(true);
  return (
      <div>
      <h1>Active User</h1>
      {
        isActive? 
          <p>User is Active Now.....</p> 
          :
          <p>User is Offline Now...</p>
      }
    </div>
  )
}

export default App;

Rendering List

In React, we use the map function to render a list of components. We can loop through arrays or an array of objects with this method. Here we need to pass a key attribute for all the returned elements from the map function. This key should be a unique identifier. Below is an example of a Rendering List in React:

const App = () => {
  const todos = [
    {
      id: 0,
      title: "Go to Gym",
    },
    {
      id: 1,
      title: "Make Tea",
    },
  ];

  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo.id}>{todo.title}</li>
      ))}
    </ul>
  );
};

export default App;

Why should indexes not be used as keys?

In React, we use the index of an element as a key attribute. But this is an anti-pattern. We shouldn’t do this. For elements, having key as an index, every time we add a new element or delete an existing element from the list, other element keys may change. This results re-rendering of the whole list. And we always need to avoid unnecessary re-renders in our front end. So, always use a unique id field as the key, not the index.

Summary

In this blog, We have discussed Conditional Rendering, Logical And Operator, Ternary Operator, Rendering Lists and why should indexes not be used as keys. To learn more about Software Enginnering and Frontend Development follow me on Hashnode.

G

Good to know:

In React, we use the index of an element as a key attribute. But this is an anti-pattern. We shouldn’t do this

D

Thanks Gemma Black, Yes, this does a lot of unnecessary re-renders.

1

More from this blog

D

Debajit Mallick's Blog

19 posts

I am a Software Engineer with 2+ years of experience. Currently, I am working at P360 as a Software Engineer. My expertise is in Frontend Web Development.

I am very active in technical communities. I am the Organizer of GDG Siliguri, Ex β-MLSA, Ex Hack Club Lead, and Ex GSSOC Ambassador.

Also, I am a Tech Speaker too. I have given technical talks at many events like FrontendDays Siliguri, GDG Bhopal, GDSC WOW KOLKATA, JWOC, Azure Devday, Hack Club SIT, GirlScript Siliguri, GDSC SIT, Codecademy Frontend Marathon and many more.

I also like to participate in Hackathons and Open Source events. I won the Smart India Hackathon 2020 and contributed to HacktoberFest 2019, HacktoberFest 2020, JWOC and GWOC. Also, I mentored a team for Smart India Hackathon 2022 that later won the Hackathon.