Lists in React

Author
By Darío Rivera
Posted On in React

In a previous article, we explored State in React using the useState hook, which allows us to store and update dynamic data inside React components. In real applications, we work most of the time with lists of data. Today, we'll learn how to display lists of items by using JavaScript expressions inside JSX.

We can leverage the JavaScript map function to transform an array of items into an array of JSX tags. Let's take a look at the following example.

function App() {
  const fruits = ["Apple", "Banana", "Orange"];

  return (
    <ul>
      {fruits.map(fruit => (
        <li key={fruit}>{fruit}</li>
      ))}
    </ul>
  )
}

One important thing to notice is the use of a key. This is something React requires to map those items later with its array. It prevents errors when re-ordering, deleting, or adding new items in the UI. We can also improve readability for the example above by creating a variable for the JSX tags in the list as follows.

function App() {
  const fruits = ["Apple", "Banana", "Orange"];

  const listItems = fruits.map(fruit =>
    <li key={fruit}>{fruit}</li>
  );
  
  return <ul>{listItems}</ul>
}

Let's check how does this look in CodePen.


Rendering Lists of Objects

In real applications, we usually work with objects instead of plain strings:

function App() {
  const users = [
    { id: 1, name: "Alice" },
    { id: 2, name: "Bob" },
    { id: 3, name: "Charlie" },
  ];
  
  const usersList = users.map(user =>
    <li key={user.id}>{user.name}</li>
  );

  return <ul>{usersList}</ul>
}

Acerca de Darío Rivera

Author

Application Architect at Elentra Corp . Quality developer and passionate learner with 10+ years of experience in web technologies. Creator of EasyHttp , an standard way to consume HTTP Clients.

LinkedIn Twitter Instagram

Sólo aquellos que han alcanzado el éxito saben que siempre estuvo a un paso del momento en que pensaron renunciar.