Rendering lists in React is a common task that can be accomplished using the .map() method to iterate over an array and return a component for each item in the array. Here’s a step-by-step guide to rendering lists in React:
Choosing the Right Key
First, ensure you have a React app set up. If not, you can create one using Create React App:
Example with Static Data
import React from 'react';
const ItemList = () => {
const items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
];
return (
{items.map(item => (
- {item.name}
))}
);
};
export default ItemList;
Example with Dynamic Data
import React, { useState } from 'react';
const ItemList = () => {
const [items, setItems] = useState([
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
]);
const addItem = () => {
const newItem = { id: items.length + 1, name: `Item ${items.length + 1}` };
setItems([...items, newItem]);
};
return (
{items.map(item => (
- {item.name}
))}
);
};
export default ItemList;
Here’s a final example showing why unique keys are important:
You can define the list data either in the state or as a static array. Here’s an example with a static array:
import React, { useState } from 'react';
const ItemList = () => {
const [items, setItems] = useState([
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
]);
const shuffleItems = () => {
setItems([...items.sort(() => Math.random() - 0.5)]);
};
return (
{items.map(item => (
- {item.name}
))}
);
};
export default ItemList;
- Always use a unique identifier from your data as the key.
- Avoid using indices as keys, especially if the list can change.
- Using keys helps React optimize rendering and maintain component state properly.