Curriculum
Course: React
Login

Curriculum

React

Text lesson

React Lists

In React, lists are rendered using some form of loop, with the JavaScript map() array method being the preferred approach.

If you need a refresher on the map() method, refer to the ES6 section.

Example:

Let’s display all the cars from our garage.

 function Car(props) {
 return <li>I am a { props.brand }</li>;
}

function Garage() {
 const cars = ['Ford', 'BMW', 'Audi'];
 return (
    <>
      <h1>Who lives in my garage?</h1>
      <ul>
        {cars.map((car) => <Car brand={car} />)}
      </ul>
    </>
 );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);

When you run this code in your create-react-app, it will work but you’ll receive a warning indicating that the list items are missing a “key” prop.

Keys

Keys help React track elements so that only updated or removed items are re-rendered, and they must be unique among siblings but can be duplicated globally.

Ideally, the key should be a unique ID for each item; as a last resort, you can use the array index as a key.

Example:

Let’s update our previous example to include keys.

function Car(props) {
 return <li>I am a { props.brand }</li>;
}

function Garage() {
 const cars = [
    {id: 1, brand: 'Ford'},
    {id: 2, brand: 'BMW'},
    {id: 3, brand: 'Audi'}
 ];
 return (
    <>
      <h1>Who lives in my garage?</h1>
      <ul>
        {cars.map((car) => <Car key={car.id} brand={car.brand} />)}
      </ul>
    </>
);
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);