0
0
Reactframework~5 mins

Map function usage in React

Choose your learning style9 modes available
Introduction

The map function helps you create a list of elements from an array easily. It saves time and keeps your code clean.

When you want to show a list of items like names or tasks on the screen.
When you need to turn data into React components dynamically.
When you want to repeat a UI pattern for each item in a collection.
When you want to update or transform each item in an array before showing it.
Syntax
React
array.map(item => <Component key={item.id} prop={item.value} />)
Always add a unique key prop to each element inside map for React to track items efficiently.
The map function returns a new array with the results of calling a function on every element.
Examples
This creates a list of <li> elements showing numbers 1, 2, and 3.
React
const numbers = [1, 2, 3];
const listItems = numbers.map(num => <li key={num}>{num}</li>);
Here, we greet each name with a paragraph. Using index as key is okay if items won't reorder.
React
const names = ['Anna', 'Bob', 'Cara'];
const nameList = names.map((name, index) => <p key={index}>Hello, {name}!</p>);
Sample Program

This React component shows a list of fruits using map. Each fruit becomes a list item with a unique key.

React
import React from 'react';

export default function FruitList() {
  const fruits = ['Apple', 'Banana', 'Cherry'];
  return (
    <ul>
      {fruits.map((fruit, idx) => (
        <li key={idx}>{fruit}</li>
      ))}
    </ul>
  );
}
OutputSuccess
Important Notes

Keys help React update only changed items, improving performance.

Never use random numbers or Math.random() as keys because keys must be stable.

Map does not change the original array; it creates a new one.

Summary

Use map to turn arrays into lists of React elements.

Always provide a unique key prop for each element inside map.

Map keeps your UI code simple and easy to read.