React

Lists & Keys in React

Rendering lists of data is one of the most common tasks in any React app.

React uses .map() to render multiple components or elements from an array.

โœ… Basic List Rendering

function FruitsList() {
  const fruits = ["Apple", "Banana", "Mango"];

  return (
    <ul>
      {fruits.map((fruit, index) => (
        <li key={index}>{fruit}</li>
      ))}
    </ul>
  );
}

๐Ÿ” Explanation:

  • fruits.map(...) loops through each fruit
  • Each <li> gets a unique key
  • key helps React identify items when the list changes

โœ… Rendering Custom Components from a List

You can render a component instead of plain <li>.

function UserCard({ name }) {
  return <p>Hello, {name}!</p>;
}

function App() {
  const users = ["Alice", "Bob", "Charlie"];

  return (
    <div>
      {users.map((user, i) => (
        <UserCard key={i} name={user} />
      ))}
    </div>
  );
}

โœ… Each UserCard gets its own name from the array.

โœ… Why key is Important

React needs a unique key for each item so it can:

  • Track which items changed, added, or removed
  • Avoid re-rendering the whole list

Bad keys:

  • Using random values (e.g., Math.random())

Good keys:

  • Use a unique ID from your data (like user.id)
  • Use index only if the list is static and never changes

Keep Learning ๐Ÿ™‚

Leave a Reply

Your email address will not be published. Required fields are marked *