Rendering lists in React is a common task when working with dynamic data. React simplifies this process using JavaScript’s map()
array method. This approach allows you to create reusable components for each item in your list, making your code cleaner and more maintainable.
Rendering Lists #
You can use the map()
method to loop through an array and render a React component for each element.
Example: Rendering a list of cars:
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, index) => (
<Car key={index} brand={car} />
))}
</ul>
</>
);
}
// Rendering the component
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
Output:
This code will display a list of car brands:
- Ford
- BMW
- Audi
Keys in React #
React requires unique keys for each list item to efficiently track and update changes in the DOM.
Why Are Keys Important?
Keys help React identify which items have changed, been added, or been removed. This allows React to re-render only the necessary components, improving performance.
Best Practices for Keys:
- Use a unique identifier, like an
id
, for each item in the list. - As a fallback, you can use the array index as the key, but this is discouraged for lists that may change dynamically.
Example with Keys #
Let’s enhance the previous example by adding unique keys to each item.
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>
</>
);
}
// Rendering the component
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
Output:
Each car in the array will render with a unique key based on its id
.
Summary #
- Rendering Lists: Use the
map()
method to iterate through arrays and render components dynamically. - Keys: Assign a unique key to each item to improve React’s efficiency and performance.
- Best Practices: Always use a unique identifier (like
id
) instead of the array index for keys whenever possible.
By using React lists effectively, you can create scalable, dynamic, and interactive components for your applications.
Want to learn React with an instructor, either offline or online? Find experienced tutors near you and join Coaching Wallah—completely free for students!
Leave your comment