A2oz

How Do You Pass an Array of Objects in React?

Published in React 2 mins read

You can pass an array of objects in React using props, just like you would pass any other data type. Here's how:

1. Create an Array of Objects in the Parent Component

import React, { useState } from 'react';

function ParentComponent() {
  const [items, setItems] = useState([
    { id: 1, name: 'Item 1' },
    { id: 2, name: 'Item 2' },
  ]);

  return (
    <div>
      <ChildComponent items={items} />
    </div>
  );
}

2. Pass the Array as a Prop to the Child Component

In the ParentComponent, you pass the items array as a prop to the ChildComponent.

3. Access the Array in the Child Component

In the ChildComponent, you can access the items array using props.items.

import React from 'react';

function ChildComponent(props) {
  return (
    <ul>
      {props.items.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

Example

In this example, the ParentComponent creates an array of objects with id and name properties. It then passes this array as a prop to the ChildComponent. The ChildComponent iterates over the array using map() and renders each item as a list item.

Practical Insights

  • Use key Prop: When mapping over an array of objects, always provide a unique key prop for each element. This helps React efficiently identify and update the list items.
  • Immutable Data: In React, it's generally best to treat data as immutable. When modifying an array, create a new array instead of directly modifying the existing one.

Related Articles