0
0
ReactHow-ToBeginner · 3 min read

How to Render List in React: Simple Syntax and Example

In React, you render a list by using the map() method on an array to create an array of JSX elements. Each element must have a unique key prop to help React track items efficiently.
📐

Syntax

Use the map() method on your array to return JSX elements. Each element needs a unique key prop to identify it.

  • array.map(item => <Element key={uniqueKey}>...</Element>): loops over array
  • key: unique identifier for each element
  • JSX element: what you want to render for each item
jsx
const listItems = items.map(item => <li key={item.id}>{item.name}</li>);
💻

Example

This example shows how to render a list of fruits using map(). Each fruit is displayed as a list item with a unique key.

jsx
import React from 'react';

export default function FruitList() {
  const fruits = [
    { id: 1, name: 'Apple' },
    { id: 2, name: 'Banana' },
    { id: 3, name: 'Cherry' }
  ];

  return (
    <ul>
      {fruits.map(fruit => (
        <li key={fruit.id}>{fruit.name}</li>
      ))}
    </ul>
  );
}
Output
<ul><li>Apple</li><li>Banana</li><li>Cherry</li></ul>
⚠️

Common Pitfalls

Common mistakes when rendering lists in React include:

  • Not providing a key prop or using an index as key, which can cause rendering bugs.
  • Mutating the original array instead of creating a new one.
  • Returning non-JSX values inside map().
jsx
/* Wrong: Using index as key can cause issues when list changes */
const listItemsWrong = items.map((item, index) => <li key={index}>{item.name}</li>);

/* Right: Use a unique stable id as key */
const listItemsRight = items.map(item => <li key={item.id}>{item.name}</li>);
📊

Quick Reference

  • Always use key prop with unique and stable values.
  • Use map() to transform arrays into JSX lists.
  • Do not mutate arrays directly when rendering.
  • Wrap list items in a container element like <ul> or <div>.