React Lists


In React, you will provide lists by type of loop.

The JavaScript map() method for similar members is usually the preferred method.


If you need to update on the map() route, check the ES6 section.




Example

Let's render all of 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>
              </>
            );
          }
          
ReactDOM.render(<Garage />, document.getElementById('root'));
          

If you use this code in your create-react-app, it will work but you will receive a warning that there is no "key" provided for list items.


Keys

Keys allow React to track features. This way, if an item is updated or removed, only that item will be redirected instead of the whole list.

The keys must be different for each sibling. But they can be repeated worldwide.


Generally, the key should be a unique ID assigned to each item. As a last resort, you can use the array index as a key.



Example

Let's refactor 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>
              </>
            );
          }
          
ReactDOM.render(<Garage />, document.getElementById('root'));