Reactintermediate 8 min
Render arrays of data as components with map, and give each item a stable key.
How to turn an array into a list of elements with .map(), why every item needs a key, and how to add, remove and filter items using state.
Almost every screen shows a list: messages, products, search results. You will build them from data, and React needs a little help to update them efficiently.
In JSX you can put an array of elements inside curly braces, and React shows them all. To make that array from data, use .map():
The key prop is a unique, stable identifier for each item in the list. React uses it to match items between renders, so it can tell which item was added, moved or removed, instead of rebuilding the whole list.
item.id), not the array index, when items can be reordered or removed.To change a list in state, never modify the array directly. Create a new one:
setItems([...items, newItem])setItems(items.filter((i) => i.id !== id))items.filter(...) just before map.items holds objects with an id and text..map turns each object into an <li> with key={item.id}.add creates a new array with the spread operator and appends the new item, which tells React the state changed.remove uses .filter to build a new array without that id.remove with its own item.id, using an arrow function so it only runs on click.Type an item and press Add, then remove some. Add a "Clear all" button that calls setItems([]).
push. Create a new array instead.remove(item.id) directly in onClick so it runs on render. Wrap it in an arrow function..map and give each item a unique, stable key.filter.Next: running code after render with useEffect.
<ul>
{names.map((name) => <li key={name}>{name}</li>)}
</ul>function App() {
const [items, setItems] = useState([
{ id: 1, text: "Learn JSX" },
{ id: 2, text: "Learn props" },
]);
const [text, setText] = useState("");
const [nextId, setNextId] = useState(3);
function add() {
if (text.trim() === "") return;
setItems([...items, { id: nextId, text }]);
setNextId(nextId + 1);
setText("");
}
function remove(id) {
setItems(items.filter((item) => item.id !== id));
}
return (
<div style={{ fontFamily: "system-ui" }}>
<input value={text} onChange={(e) => setText(e.target.value)} placeholder="New item" />
<button onClick={add}>Add</button>
<ul>
{items.map((item) => (
<li key={item.id}>
{item.text} <button onClick={() => remove(item.id)}>x</button>
</li>
))}
</ul>
<p>{items.length} items</p>
</div>
);
}