loading

React Lists


In React, you will render lists using a loop.

The JavaScript map() array technique is often preferable.

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


Example

Let’s render every vehicle in 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 />);
				
			

This code will function in your create-react-app when you run it, but a warning about the lack of a “key” for the list items will appear.

Keys

Keys enable React to keep track of elements. This manner, if an item is modified or removed, only that item will be re-rendered, not the entire list.

Keys must be unique to each sibling. However, they can be reproduced globally.

In general, the key should be a unique ID for each item. As a final resort, utilize the array index as a key.

Example

Let us rewrite our earlier example to incorporate 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 />);
				
			

If you want to communicate a variable rather than a string, as in the example above, simply place the variable name inside curly brackets:

Example

Create a variable called carName and pass it to the Car component:

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

function Garage() {
  const carName = "Ford";
  return (
    <>
      <h1>Who lives in my garage?</h1>
      <Car brand={ carName } />
    </>
  );
}

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

Alternatively, if it were an object:

Example

Create an object called carInfo and send it to the Car component.

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

function Garage() {
  const carInfo = { name: "Ford", model: "Mustang" };
  return (
    <>
      <h1>Who lives in my garage?</h1>
      <Car brand={ carInfo } />
    </>
  );
}

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

React Lists

Or copy link

Explore Topic