{

How to render an array of objects in react?| Array map example in react


This is a short tutorial on how to render an array of objects in React component render component. We have an array of object data either coming from API or fixed.

For example,

employeeList = [
    {
        name: 'John',
        email: 'john@gmail.com'
    },

    {
        name: 'Ram  ',
        email: 'ram@gmail.com'
    }
]

We can use the Array map function to iterate each object of an array.

Let’s see how to iterate using the Array.map method in react component.

React class component to render an array of objects using the map method

  • Created a react component app.jsx

  • we have an array of objects stored in react state object

  • In the render method, Iterated array of objects using the map method and construct the result object

  • In the render method add this result using the javascript expression syntax

import "./styles.css";

import React, { Component } from 'react';
import { render } from 'react-dom';

export default class App extends Component {
    constructor(props) {
    super(props);
    this.state = {
      data: [{
        name: 'John',
        email: 'john@gmail.com'
    },{
        name: 'Ram  ',
        email: 'ram@gmail.com'
    }]
    }
    }
  render() {
    const emps = this.state.data;
const result=emps.map((emp,index) => <li key={index}>{emp.name}</li>);

         
    return <ul>{result}</ul>;
  }
}

This prints the ordered list of objects values

Stateless React functional component to display an array of objects

This is a stateless functional component.

  • In the Return functional component, We have used the map to iterate and construct li object, print using javascript expression
import "./styles.css";

export default function App() {
  const employeeList = [
    {
      name: "John",
      email: "john@gmail.com"
    },

    {
      name: "Ram  ",
      email: "ram@gmail.com"
    }
  ];
  return (
    <ul>
      {this.employeeList.map((emp, index) => (
        <li key={index}>{emp.name}</li>
      ))}
      ;
    </ul>
  );
}

Conclusion

In this tutorial, You learned how to render an array of objects in stateful and stateless components

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.