Approach 4 Using React.Children.map()
- It is a utility function in React
- It is used to iterate over the child component
- It takes a callback function as an argument
- The callback functions takes child and index as arguments to iterate over the child components and modify it
Syntax:
React.Children.map(children, (child, index) => (
// write your code here
))
Example: Below is the example of using React.Children.map():
import React from 'react';
const arrayList = ['List Item 1', 'List Item 2', 'List Item 3'];
const UsingReactChildrenMap = ({ children }) => {
const modifiedChildren =
React.Children.map(children, (child, index) => (
<div key={index}>Modified {child}</div>
));
return <div>{modifiedChildren}</div>;
};
const App = () => (
<div>
<h2>
Using React.Children.map()
</h2>
<UsingReactChildrenMap>
<div style={
{
display: 'inline-block',
marginRight: '10px'
}}>
{arrayList[0]}
</div>
<div style={
{
display: 'inline-block',
marginRight: '10px'
}}>
{arrayList[1]}
</div>
<div style={
{
display: 'inline-block',
marginRight: '10px'
}}>
{arrayList[2]}
</div>
</UsingReactChildrenMap>
</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
Contact Us