0
0
ReactHow-ToBeginner · 3 min read

How to Pass Array as Prop in React: Simple Guide

In React, you pass an array as a prop by including it inside curly braces {} when using the component, like <MyComponent items={myArray} />. Inside the component, you access it via props.items or by destructuring the props object.
📐

Syntax

To pass an array as a prop, use the component tag with the prop name and assign the array inside curly braces {}. Inside the component, access the array from props or by destructuring.

  • Parent component: Pass array with propName={arrayVariable}.
  • Child component: Receive props and use props.propName or { propName }.
jsx
function ChildComponent({ items }) {
  return (
    <ul>
      {items.map((item, index) => (
        <li key={index}>{item}</li>
      ))}
    </ul>
  );
}

function ParentComponent() {
  const myArray = ['Apple', 'Banana', 'Cherry'];
  return <ChildComponent items={myArray} />;
}
💻

Example

This example shows a parent component passing an array of fruits to a child component, which renders them as a list.

jsx
import React from 'react';

function FruitList({ fruits }) {
  return (
    <ul>
      {fruits.map((fruit, index) => (
        <li key={index}>{fruit}</li>
      ))}
    </ul>
  );
}

export default function App() {
  const fruitArray = ['Mango', 'Orange', 'Pineapple'];
  return (
    <div>
      <h1>Fruit List</h1>
      <FruitList fruits={fruitArray} />
    </div>
  );
}
Output
<h1>Fruit List</h1><ul><li>Mango</li><li>Orange</li><li>Pineapple</li></ul>
⚠️

Common Pitfalls

Common mistakes when passing arrays as props include:

  • Passing the array as a string instead of inside curly braces, which passes the literal text, not the array.
  • Forgetting to add a unique key prop when rendering lists inside the child component.
  • Mutating the array inside the child component, which can cause unexpected bugs.
jsx
/* Wrong way: passing array as string */
<ChildComponent items="['a', 'b', 'c']" />

/* Right way: pass array variable inside curly braces */
const arr = ['a', 'b', 'c'];
<ChildComponent items={arr} />
📊

Quick Reference

StepDescriptionExample
1Create an array in parentconst arr = ['x', 'y', 'z'];
2Pass array as prop with curly braces
3Receive prop in child componentfunction MyComponent({ items }) { ... }
4Render array items with map and keysitems.map((item, i) =>
  • {item}
  • )

    Key Takeaways

    Always pass arrays as props inside curly braces to send the actual array, not a string.
    Use destructuring in the child component to access the array prop cleanly.
    When rendering arrays, always provide a unique key for each element.
    Avoid mutating props inside child components to keep React state predictable.