React Lists and Keys: Manage Dynamic Elements

react lists and keys

React Lists and Keys help you show many items and keep each item tracked for updates.

What do Lists and Keys Mean in React?

React can show many items on a page, and each item holds data for a user. Lists in React allow you to draw items from data arrays and show them in a clean order.

A key in React helps the library know which item changes or stay in the list after updates. This process lets React update only what has changed instead of redrawing all items.

Here is a quick example:

const names = ['Ali', 'Sara', 'John'];
function NameList() {
  return (
    <ul>
      {names.map(name => <li key={name}>{name}</li>)}
    </ul>
  );
}

This example shows you how a small array can draw items on a web page. Each item in the array has a unique key so React can track it during changes.

A news site can show new articles as they arrive without removing old ones. Keys help React know which article is new and which article stays on the page.

Keys help React match items between renders, so it updates only what must change. Without keys, React may reorder items or create wrong updates, which can break the page view.

How to Use map() to Render Lists in React

The map() method in JavaScript loops over arrays and returns new elements. React uses map() to draw each element of the list on the page with a key.

Here is an example:

const fruits = ['Apple', 'Orange', 'Mango'];
function FruitList() {
  return (
    <ul>
      {fruits.map(fruit => <li key={fruit}>{fruit}</li>)}
    </ul>
  );
}

This example shows a simple array with three fruits drawn on the page. React uses map() to loop through each fruit and a key to mark each item.

Here is another example:

const users = [
  { id: 1, name: 'Ali' },
  { id: 2, name: 'Sara' }
];
function UserList() {
  return (
    <div>
      {users.map(user => (
        <p key={user.id}>{user.name}</p>
      ))}
    </div>
  );
}

This example shows how to render objects that hold an id and name for each user. React uses the id as a key to keep each user stable after any change.

Examples

Add Items to a List:

const [items, setItems] = React.useState(['Pen', 'Book']);
function AddItem() {
  const addNew = () => setItems([...items, 'New']);
  return (
    <div>
      <button onClick={addNew}>Add</button>
      <ul>
        {items.map((item, index) => <li key={index}>{item}</li>)}
      </ul>
    </div>
  );
}

This example shows a stateful list that can add a new item. React tracks each item by index, so a new one can appear without breaking other items.

Nested Lists:

const categories = [
  { id: 1, name: 'Fruits', items: ['Apple', 'Mango'] },
  { id: 2, name: 'Tools', items: ['Hammer', 'Saw'] }
];
function NestedList() {
  return (
    <div>
      {categories.map(cat => (
        <div key={cat.id}>
          <h3>{cat.name}</h3>
          <ul>
            {cat.items.map((item, idx) => <li key={idx}>{item}</li>)}
          </ul>
        </div>
      ))}
    </div>
  );
}

This example shows a list inside another list. Each category uses an id as a key, and each nested item uses an index to help React track each one.

Complex Component Lists:

function Product({ product }) {
  return <div>{product.title} - {product.price}</div>;
}
const products = [
  { id: 1, title: 'Phone', price: '$200' },
  { id: 2, title: 'Tablet', price: '$300' }
];
function ProductList() {
  return (
    <div>
      {products.map(prod => <Product key={prod.id} product={prod} />)}
    </div>
  );
}

This example shows how you can render a custom component for each product. React uses the id to keep each product in place even when data updates.

Wrapping Up

You learned how lists work in React and how keys help React keep track of items.

Here is a quick recap:

  • You can show lists in React with map(). Each item needs a key, and keys from data keep items stable after changes.

FAQs

What are React Lists and Keys?

React Lists and Keys allow developers to display multiple elements. Keys help React identify which items change.
  • Lists show data with map() in React
  • Keys give each element a unique identity

How do you render a list in React?

Use the map() function to render each item:

const items = ['Apple','Banana','Mango'];
<ul>
  {items.map((item,index)=>
    <li key={index}>{item}</li>
  )}
</ul>
This assigns a key to each <li> element.

Why are keys important in React lists?

Keys help React track changes. Without keys React may re-render items incorrectly.
  1. Keys must be unique
  2. Keys improve performance
  3. Keys allow efficient updates

What are common mistakes with React keys?

  • Using index as key in dynamic lists
  • Using duplicate keys
  • Omitting keys on mapped elements

// Wrong
items.map((item,index)=><li key={index}>{item}</li>)
// Right
items.map(item=><li key={item.id}>{item.name}</li>)

Similar Reads

React Components: A Complete Tutorial for Beginners

In this tutorial, you will learn what components are in React and how to build them. Also, how to pass…

React Conditional Rendering Examples

React conditional rendering is a way to show different parts of a page. Click here to see how it works…

How to Install React on Ubuntu, Windows and MacOS

Through this article, you will learn how to install React on common operating systems such as Windows, macOS, and Ubuntu.…

State in React Step by Step with Examples

State in React lets a component hold data that can change over time. You can use it to track values…

Learn JSX in React: Syntax, Rules, and Examples

JSX helps write React UI with HTML-like syntax. It links JavaScript logic with markup in one view. What is JSX…

Forms in React: How to Create and Manage User Inputs

Forms in React allow a page to take data from a user. A developer uses them to show fields, take…

How to Render HTML Elements in React.js

Rendering HTML in React might sound like a complicated task, but it’s actually quite simple once you understand the basics.…

Events in React: A Complete Guide for Beginners

Events in React are actions that a user does with a page. A user can click a button or type…

Props in React explained with examples

Props in React pass data from one part to another part. They let you build parts that reuse data and…

React JS Introduction: What is React? the JavaScript Library

In this introduction, you will understand what React JS is and learn how to use NPM commands to get started…

Previous Article

How to Open Link in New Tab with HTML Target

Next Article

How to Drop Database in SQL Server

Write a Comment

Leave a Comment

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


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.