How to Render a List Using map() in React

At the end of the previous lesson, we were able to conditionally render a user and the corresponding status, represented using a green check mark. This brings us to our next question, what if there are more than one user?

For example, here is an array of objects containing information of different users and their corresponding email addresses and status:

javascript
1const users = [
2  { id: 1, name: "Alice", email: "alice@example.com", isActive: true },
3  { id: 2, name: "Bob", email: "bob@example.com", isActive: true },
4  { id: 3, name: "Charlie", email: "charlie@example.com", isActive: false },
5  { id: 4, name: "Diana", email: "diana@example.com", isActive: false },
6];

How would you display this information using React and JSX?

Using map()

The first thing you could do is using the map() method. Recall that map() is one of the built-in JavaScript methods used to perform actions on every element in an array, and then return the result in an new array.

In this case, we can transform this users array into an array of JSX element, which can then be rendered by React.

jsx
1function App() {
2  const users = [
3    { id: 1, name: "Alice", email: "alice@example.com", isActive: true },
4    { id: 2, name: "Bob", email: "bob@example.com", isActive: true },
5    { id: 3, name: "Charlie", email: "charlie@example.com", isActive: false },
6    { id: 4, name: "Diana", email: "diana@example.com", isActive: false },
7  ];
8
9  return (
10    <ul>
11      {users.map((user) => (
12        <li key={user.id}>
13          {user.name} - {user.email} {user.isActive && "✅"}
14        </li>
15      ))}
16    </ul>
17  );
18}
19
20export default App;

React render list

Adding filters

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉