React Lists & Keys
Understanding React Lists
In React, rendering lists typically involves iterating through an array using a loop.
The JavaScript map() method is the most commonly used approach for dynamically generating elements.
If you're unfamiliar with the map() function, reviewing ES6 concepts can provide clarity.
Executing the following code inside a Create React App setup will function correctly; however, a warning will appear due to missing "key" properties for individual list elements.
Providing a unique key enhances performance by helping React track element changes efficiently.
Here's a unique example similar to your Car and Garage components, but using animals in a zoo instead:
Example:
function Animal(props) { return <li>The zoo has a {props.name}. </li>; } function Zoo() { const animals = ["Lion", "Elephant", "Giraffe", "Zebra"]; return ( <> <h1>Animals in the Zoo </h1> <ul> {animals.map((animal, index) => ())} </ul> </> ); }
Explanation:
- The Animal component receives a name prop and renders an individual list item.
- The Zoo component contains an array of animal names.
- The map() method dynamically creates
components for each item. - The key prop (using index) helps React track changes efficiently.
Understanding React Keys
Keys help React identify individual elements, ensuring that only modified or removed items are updated instead of reprocessing the entire list.
Each sibling in a list must have a distinct key, though duplicates can exist across different lists.
Ideally, a key should be a unique identifier assigned to every item.
If no unique ID is available, the array index can be used as a fallback, though this is not always recommended for dynamic lists.
Here's a unique example using planets in the solar system, ensuring each item has a unique key:
Example:
function Planet(props) { return<li>{props.name} is a planet. </li>; } function SolarSystem() { const planets = [ { id: 101, name: "Mercury" }, { id: 102, name: "Venus" }, { id: 103, name: "Earth" }, { id: 104, name: "Mars" }, { id: 105, name: "Jupiter" } ]; return ( <> <h1>Planets in the Solar System</h1> <ul> {planets.map((planet) => ( <Planet key={planet.id} name={planet.name} /> ))} </ul> </> ); } const root = ReactDOM.createRoot(document.getElementById("root")); root.render();
Explanation:
- The Planet component renders each planet name.
- The SolarSystem component holds an array of planet objects, each with a unique id.
- The map() function creates a list where each item has a unique key,ensuring efficient rendering.
Previous Next