Home >Web Front-end >JS Tutorial >How to Render an Array of Objects in React Using the Map Function?
Rendering an Array of Objects in React
Rendering lists in React is essential for displaying dynamic data. This guide showcases how to efficiently render an array of objects in React using the map function.
Approach:
Consider the following React component:
<code class="javascript">class First extends React.Component { render() { const data = [{ name: "test1" }, { name: "test2" }]; const listItems = data.map((d) => <li key={d.name}>{d.name}</li>); return ( <div> Hello </div> ); } }</code>
There are two primary approaches to rendering the array of objects:
First Approach:
Assign the mapped array to a variable and return it within the render function:
<code class="javascript">render() { const data =[{"name":"test1"},{"name":"test2"}]; const listItems = data.map((d) => <li key={d.name}>{d.name}</li>); return ( <div> {listItems } </div> ); }</code>
Second Approach:
Directly embed the map function within the return statement:
<code class="javascript">render() { const data =[{"name":"test1"},{"name":"test2"}]; return ( <div> {data.map(function(d, idx){ return (<li key={idx}>{d.name}</li>) })} </div> ); }</code>
The above is the detailed content of How to Render an Array of Objects in React Using the Map Function?. For more information, please follow other related articles on the PHP Chinese website!