Home >Web Front-end >JS Tutorial >How to Display an Array of Objects in React?

How to Display an Array of Objects in React?

Barbara Streisand
Barbara StreisandOriginal
2024-11-07 21:13:021004browse

How to Display an Array of Objects in React?

How to Display an Array of Objects in React

In React, displaying an array of objects requires a mapping process to transform the array into visible elements.

Mapping Arrays to Rendered Items

To render an array of objects, you can utilize the .map() function. This function takes a callback function that accepts individual array elements as input.

Option 1: Storing Mapped Items in a Variable

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

Here, the listItems variable stores the mapped elements, which are then rendered within a

.

Option 2: Direct Mapping in the Return

Alternatively, you can eliminate the need for an intermediary variable:

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

In this variation, the mapping function is directly called within the return statement.

Keys for Unique Identifiers

When rendering arrays, it's essential to provide unique keys for each item. In both options, a key is added to each rendered element to optimize rendering performances and allow for efficient updates.

The above is the detailed content of How to Display an Array of Objects in React?. 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