← React Beginner Questions - Set 5 Q43
React Beginner Questions - Set 5
Keys let React follow an item through inserts, removals and reordering. This example keeps a text input's state attached to the right item.
import { useState } from 'react';
export default function Rows() {
const [rows, setRows] = useState([
{ id: 'a', name: 'Ana' },
{ id: 'b', name: 'Luis' },
]);
return (
<>
<button onClick={() => setRows(r => [{ id: 'z', name: 'New' }, ...r])}>Add on top</button>
{rows.map(row => (
<label key={row.id}>
{row.name}: <input placeholder="note" />
</label>
))}
</>
);
}