In React, rendering lists usually involves some form of loop. The map()
array method in JavaScript is commonly used for this purpose.
Rendering Lists with map()
The map()
method is often the go-to for rendering lists in React. If you need a refresher on how map()
works, check out the ES6 section.
Let’s create a list of vehicles to display, When this code runs in your React application, it will function, but you’ll see a warning about missing keys for list items.
function Vehicle(props) { return <li>This is a {props.type}</li>; } function ParkingLot() { const vehicles = ['Toyota', 'Honda', 'Chevy']; return ( <> <h1>Vehicles in the Parking Lot:</h1> <ul> {vehicles.map((vehicle, index) => <Vehicle key={index} type={vehicle} />)} </ul> </> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<ParkingLot />);
Understanding Keys
Keys are essential for React to keep track of elements. This allows React to update or remove only the necessary items rather than re-rendering the entire list. Keys must be unique among siblings but can be reused globally.
Usually, the key should be a unique identifier for each item. As a fallback, the array index can be used.
Let’s revise the previous example to include keys:
function Vehicle(props) { return <li>This is a {props.type}</li>; } function ParkingLot() { const vehicles = [ { id: 1, type: 'Toyota' }, { id: 2, type: 'Honda' }, { id: 3, type: 'Chevy' } ]; return ( <> <h1>Vehicles in the Parking Lot:</h1> <ul> {vehicles.map((vehicle) => <Vehicle key={vehicle.id} type={vehicle.type} />)} </ul> </> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<ParkingLot />);