Explain the Map usage in react and give an example for the same.
Manoj Kumar Duraisamy
Select an image from your device to upload
An example of how you can use map in React to render a list of items:
import React from 'react';const items = ['Apple', 'Banana', 'Orange'];const ItemList = () => { return ( <ul> {items.map((item, index) => ( <li key={index}>{item}</li> ))} </ul> );};export default ItemList;
import React from 'react';
const items = ['Apple', 'Banana', 'Orange'];
const ItemList = () => {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
};
export default ItemList;
In this example, we have an array of items that we want to render as a list. We use the map method to iterate over the items array, and for each item in the array, we return a new li element with the item’s value as the content. We are also using the key prop to give each li element a unique identifier. This is important in React to help React identify which items have changed when re-rendering the list.
In React, map is a JavaScript array method that is often used to iterate over an array and return a new array with transformed elements. It is commonly used in React to generate a list of components based on an array of data.