How to render the lists in ReactJs

rathoremanpreet

Manpreet Singh

Posted on May 14, 2023

How to render the lists in ReactJs

Rendering lists of data is one of the most common tasks in web development. In ReactJS, rendering lists can be done using various approaches. In this blog post, we will explore how to render lists in ReactJS.

Method 1: Using for loop

const fruits = ["Apple", "Banana", "Orange"];

const fruitList = [];

for (let i = 0; i < fruits.length; i++) {
  fruitList.push(<li>{fruits[i]}</li>);
}

return <ul>{fruitList}</ul>;
Enter fullscreen mode Exit fullscreen mode

Method 2: Using Map

Another way to render lists in ReactJS is by using the map method. In this method, we create an array of elements using the map method and then render them on the page.

const fruits = ["Apple", "Banana", "Orange"];

return (
  <ul>
    {fruits.map((fruit) => (
      <li>{fruit}</li>
    ))}
  </ul>
);
Enter fullscreen mode Exit fullscreen mode

Method 3: Using Array.prototype.reduce()

The reduce method is a powerful tool that can be used to render lists in ReactJS. In this method, we create an array of elements using the reduce method and then render them on the page.

const fruits = ["Apple", "Banana", "Orange"];

return (
  <ul>
    {fruits.reduce((accumulator, fruit) => (
      accumulator.push(<li>{fruit}</li>), accumulator
    ), [])}
  </ul>
);
Enter fullscreen mode Exit fullscreen mode

In this blog post, we have explored the different ways to render lists in ReactJS. Although there are several approaches to achieving this, using a map is the most common and recommended way. Using a map not only simplifies the code but also improves its readability. It is essential to choose the right approach depending on the requirements of your project.

💖 💪 🙅 🚩
rathoremanpreet
Manpreet Singh

Posted on May 14, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related