Categories
React Answers

How to Render Lists in React Components?

Spread the love

Oftentimes, we want to render lists in our React app.

In this article, we’ll look at how to render lists in our React app.

Rendering Lists in React Components

We can render lists by mapping our data to the component that we use to render the list item.

To do the mapping, we use the array’s map instance method. We can do that as follows:

import React from "react";

const persons = [
  { firstName: "Jane", lastName: "Smith" },
  { firstName: "Alex", lastName: "Jones" },
  { firstName: "May", lastName: "Wong" }
];

const Person = ({ firstName, lastName }) => (
  <div>
    {firstName} {lastName}
  </div>
);

export default function App() {
  return (
    <div>
      {persons.map((p, i) => (
        <Person {...p} key={i} />
      ))}
    </div>
  );
}

In the code above, we have the Persons array, which we call map on in App . In the map method, we pass in a callback to return the Person component with all the properties of each persons entry passed in as props.

We need the key prop so that React can identify them properly. Ideally, it’s a unique ID, but the array index can also be the value of the key prop.

Then in Person , we have the props in the parameters and we decompose the prop properties in variables with the destructuring syntax.

Therefore <Person {...p} /> is the same as:

<Person firstName={p.firstName} lastName={p.lastName} key={i} />

It’s a lot shorter if our prop name is the same as our object’s property names.

In the end, we see:

Jane Smith
Alex Jones
May Wong

displayed on the screen.

Conclusion

We can render lists by mapping our data to the component that we use to render the list item.

Leave a Reply

Your email address will not be published. Required fields are marked *