List & Keys in React: Displaying Array Data the Fun and Efficient Way

 

 

  

"If arrays are for looping, React makes them shine on screen."

Hello React Developers!

If you've ever wanted to display a list of items—names, products, or comments—in React, then you're in the right place. Today, we’re talking about Lists and Keys: the dynamic duo of displaying data from arrays.

 

What is a List in React?

A list in React means rendering multiple JSX elements based on an array of data using JavaScript’s map() method.

const fruits = ['Apple', 'Banana', 'Orange'];

<ul>
  {fruits.map(fruit => <li>{fruit}</li>)}
</ul>

 

Why Use map()?

map() is the go-to method to transform each item in an array into a JSX element. It returns a new array—exactly what React needs to render elements.

 

What is a Key?

A key is a special prop that React uses to identify which items have changed, been added, or removed. Keys help React optimize updates.

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

 

Basic Example: Fruit List

function FruitList() {
  const fruits = ['Apple', 'Banana', 'Orange'];

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

 

More Complex Example: List of Objects

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];

function UserList() {
  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

 

Should You Use Index as Key?

Using index is okay for static lists, but not recommended when the list may change (e.g., add/delete/move items). It can lead to UI bugs and incorrect rendering.

 

Using Custom Components in Lists

function Task({ name }) {
  return <li>{name}</li>;
}

function TaskList() {
  const tasks = ['Coding', 'Netflix', 'Sleep'];

  return (
    <ul>
      {tasks.map((task, i) => (
        <Task key={i} name={task} />
      ))}
    </ul>
  );
}

 

Tips & Best Practices

  •  Use unique IDs for keys
  •  Avoid using index as key (unless static)
  •  Place the key prop on the outermost mapped element
  •  Handle empty arrays gracefully

 

What Happens If You Don’t Use a Key?

React will warn you in the console:

Warning: Each child in a list should have a unique "key" prop.

 

Example: Comments with Fallback

function CommentList({ comments }) {
  if (comments.length === 0) {
    return <p>No comments yet</p>;
  }

  return (
    <ul>
      {comments.map(comment => (
        <li key={comment.id}>{comment.text}</li>
      ))}
    </ul>
  );
}

 

Dynamic List with State

function TodoApp() {
  const [tasks, setTasks] = useState(['Learn', 'Chill']);

  return (
    <div>
      <ul>
        {tasks.map((task, i) => (
          <li key={i}>{task}</li>
        ))}
      </ul>
      <button onClick={() => setTasks([...tasks, 'Coffee'])}>Add Task</button>
    </div>
  );
}

 

Case Study: Product Catalog

const products = [
  { id: 'p1', name: 'Laptop', price: 1000 },
  { id: 'p2', name: 'Mouse', price: 25 },
  { id: 'p3', name: 'Keyboard', price: 45 }
];

function ProductList() {
  return (
    <div>
      <h3>Product Catalog</h3>
      <ul>
        {products.map(p => (
          <li key={p.id}>
            {p.name} - ${p.price}
          </li>
        ))}
      </ul>
    </div>
  );
}

Displaying arrays in React is simple and powerful with map() and keys. Use them right and your UI will be smooth, efficient, and bug-free.

"React loves arrays. And arrays love good keys."

 

 

0 Comments:

Post a Comment