← React Beginner Questions - Set 5 Q43

What is the significance of the key prop in React lists?

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.

Example

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>
      ))}
    </>
  );
}

What to notice

← Back to the question list