Home >Web Front-end >JS Tutorial >How to Render an Array of Objects in React Using the Map Function?

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

DDD
DDDOriginal
2024-11-06 18:05:02368browse

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!

Statement:
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