Approach 5 Using map() and JSX Spread Attributes
- This method is used to render the components with dynamic props
- In the callback function while rendering the components props will be passed to it
- The callback function take item and index as the argument
Syntax:
const arrayListWithProps = {
prop1: 'value1',
prop2: 'value2',
prop3: 'value3'
};
arrayListWithProps.map(item => (
// write your code here
))
Example: Below is the example of using map() and JSX Spread attributes:
import React from 'react';
const araayListWithProps = [
{
id: 1,
name: 'Item 1',
color: 'lightcoral'
},
{
id: 2,
name: 'Item 2',
color: 'cadetblue'
},
{
id: 3,
name: 'Item 3',
color: 'cyan'
}
];
const ArrayListComponent = ({ name, color }) => (
<div style={
{
backgroundColor: color,
padding: '5px',
margin: '5px',
color: 'white'
}
}>
{name}
</div>
);
const App = () => (
<div>
<h2>
Using map() with JSX Spread Props
</h2>
{
araayListWithProps.map(item => (
<ArrayListComponent
key={item.id} {...item} />
))
}
</div>
);
export default App;
Output:
Different ways to render a list of items in React
This article explains the various approaches for rendering a list of items in React. Render List means displaying various items present in the list. It is a very commonly used operation in applications. React can help in the dynamic rendering of list items.
We will discuss the following approaches to render a list of items in React:
Table of Content
- Using Array.map()
- Using for loop
- Using Array.forEach()
- Using React.Children.map()
- Using map() and JSX Spread Attributes