React: How to Render an Array of Objects (Full Example)

Last updated on July 5, 2022 A Goodman Loading... Post a comment

In React, the most popular way to render an array of objects is to use the Array.map() method. This method calls a function once for each element in the array:

<div>
  {items.map((item) =>
       <div key={item.id}>{/* ... */}</div>
  )}
</div>

The complete example below will give you a better understanding of how to apply this in action.

Example

Overview

This sample app displays a list of employees of a fiction company. The array that holds the data looks like this:

const employees = [
  {
    id: 'e1',
    name: 'Person One',
    salary: 5000
  },
  /* ... */
]

Each employee has an id, a name, and a salary.

App screenshot:

The Code

The complete source code in src/App.js with explanations:

// KindaCode.com
// src/App.js

// Dummy data for the app
const employees = [
  {
    id: 'e1',
    name: 'Person One',
    salary: 5000
  },
  {
    id: 'e2',
    name: 'Person Two',
    salary: 6000
  },
  {
    id: 'e3',
    name: 'Person Three',
    salary: 4500
  },
  {
    id: 'e4',
    name: 'Person Four',
    salary: 7000
  },
  {
    id: 'kindacode.com',
    name: 'Person Five',
    salary: 8000
  }
]

function App() {
  return (
    <div style={styles.container}>
      <h1>Employee List</h1>

      {/* Render the list */}
      <div>
        {employees.map((employee) =>
          <div key={employee.id} style={styles.listItem}>
            <h3>{employee.name}</h3>
            <p>Salary: {employee.salary}</p>
          </div>)
        }
      </div>
    </div>
  );
}

// Styling 
const styles = {
  container: {
    backgroundColor: '#fff9c4',
    padding: '10px 50px 60px 50px'
  },
  listItem: {
    borderTop: '1px dashed #ccc'
  }
}

export default App;

Conclusion

You’ve learned how to conveniently render an array of objects in React with the help of the map() method. From this time forward, you can build more complex things with this technique in mind. If you’d like to explore more new and exciting stuff about modern React, take a look at the following articles:

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles