Home > Web Front-end > JS Tutorial > body text

How to Render an Array of Objects in React Using the Map Function?

DDD
Release: 2024-11-06 18:05:02
Original
289 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!