How to Display Array of Objects in React

Advertisement

When working with React, you will be required to display an array of objects in your application’s user interface. Whether you’re building a user list, a product catalog, or any other dynamic content, efficiently rendering and presenting an array of objects is a fundamental skill to master.

In this article, we will explore different methods to effectively render and display an array of objects in React.

Understanding the Array of Objects

Before we dive into the implementation, let’s briefly understand what an array of objects is. In JavaScript, an array is a collection of values, and each value can be of any data type, including objects. An array of objects is simply an array where each element is an object with key-value pairs.

For example, consider an array of user objects:

const users = [
  {
    id: 1,
    name: "John Doe",
    age: 25,
  },
  {
    id: 2,
    name: "Jane Smith",
    age: 30,
  },
  // ...
];

Each object in the array represents a user, and it contains properties like id, name, and age. Our goal is to display this array of user objects in a React component.

Mapping over the Array

The most common approach to rendering an array of objects in React is by using the map method. The map method allows us to iterate over each element of the array and return a new array with transformed values.

In our case, we can use map to iterate over the users array and create a new array of React components representing each user. Here’s an example:

import React from "react";

const UserList = () => {
  const users = [
    {
      id: 1,
      name: "John Doe",
      age: 25,
    },
    {
      id: 2,
      name: "Jane Smith",
      age: 30,
    },
    // ...
  ];
  return (
    <>
      <h1>Display Array Object</h1>
      <div>
        <h2>Mapping over the array</h2>
        <ul>
          {users.map((user) => (
            <li key={user.id}>
              <span>Name: {user.name}</span> - <span>Age: {user.age}</span>
            </li>
          ))}
        </ul>
      </div>      
    </>
  );
};

export default UserList;

In the above example, we define a UserList component that receives the users array as a prop. Inside the component, we use the map method to iterate over the array and create a list item (<li>) for each user. The key attribute is necessary to provide a unique identifier for each list item.

Conditional Rendering

Sometimes, you may want to conditionally render elements based on certain properties of the objects in the array. React provides several ways to achieve this. One common approach is using the conditional (ternary) operator (? :).

Let’s consider an example where we want to display a special message for users above a certain age. We can modify our previous code snippet to include the conditional rendering:

import React from "react";

const UserList = () => {
  const users = [
    {
      id: 1,
      name: "John Doe",
      age: 25,
    },
    {
      id: 2,
      name: "Jane Smith",
      age: 30,
    },
    // ...
  ];
  return (
    <>
      <h1>Display Array Object</h1>
      <div>
        <h2>Conditional Rendering</h2>
        <ul>
          {users.map((user) => (
            <>
              {user.age > 25 ? (
                <li key={user.id}>
                  <span>Name: {user.name}</span> -
                  <span>Age: {user.age} - More than 25 Years Old!</span>
                </li>
              ) : null}
            </>
          ))}
        </ul>
      </div>
    </>
  );
};

export default UserList;

In the updated code, we added a conditional check using the user.age property. If the age is greater than 25, we display the special message; otherwise, we render null.

Styling the Displayed Elements

To make the displayed array of objects visually appealing, we can apply styles to the rendered components. React provides different ways to add styles to components, including inline styles, CSS modules, or CSS-in-JS libraries like styled-components.

Let’s modify our UserList component to apply some basic styles using inline styles:

import React from "react";

const UserList = () => {
  const users = [
    {
      id: 1,
      name: "John Doe",
      age: 25,
    },
    {
      id: 2,
      name: "Jane Smith",
      age: 30,
    },
    // ...
  ];
  return (
    <>
      <h1>Display Array Object</h1>
      <div>
        <h2>Styling the Displayed Elements</h2>
        <ul>
          {users.map((user) => (
            <li key={user.id} style={{ marginBottom: "1rem" }}>
              <span style={{ fontWeight: "bold" }}>
                Name: {user.name}
              </span>
              <span style={{ marginLeft: "1rem", fontStyle: "italic" }}>
                Age: {user.age}
              </span>
              {user.age > 25 ? (
                <span style={{ color: "red" }}> - Special Message!</span>
              ) : null}
            </li>
          ))}
        </ul>
      </div>
    </>
  );
};

export default UserList;

In the updated code, we added inline styles using the style attribute on each element. We applied styles such as marginBottom, fontWeight, marginLeft, fontStyle, and color to demonstrate basic styling possibilities. However, for more complex styling needs, consider using CSS modules, styled-components or Tailwind CSS.

author's bio photo

Hi there! I am Avic Ndugu.

I have published 100+ blog posts on HTML, CSS, Javascript, React and other related topics. When I am not writing, I enjoy reading, hiking and listening to podcasts.