0
0
ReactHow-ToBeginner · 3 min read

How to Pass Object as Prop in React: Simple Guide

In React, you pass an object as a prop by including it inside curly braces in the component tag, like <Component propName={object} />. Inside the child component, you access it via props.propName or by destructuring the props object.
📐

Syntax

To pass an object as a prop, write the component tag with the prop name and assign the object inside curly braces. In the child component, access the object through props or by destructuring.

  • Parent: Pass object with <Child propName={object} />
  • Child: Access with props.propName or { propName } if destructured
jsx
const user = { name: 'Alice', age: 30 };

function Child(props) {
  return <div>{props.user.name} is {props.user.age} years old.</div>;
}

function Parent() {
  return <Child user={user} />;
}
💻

Example

This example shows how a parent component passes a user object as a prop to a child component, which then displays the user's name and age.

jsx
import React from 'react';

const user = { name: 'Alice', age: 30 };

function Child({ user }) {
  return (
    <div>
      <strong>{user.name}</strong> is <em>{user.age}</em> years old.
    </div>
  );
}

export default function Parent() {
  return <Child user={user} />;
}
Output
Alice is 30 years old.
⚠️

Common Pitfalls

Common mistakes include passing the object as a string instead of inside curly braces, or trying to access the prop incorrectly inside the child component.

  • Passing object as string: <Child user="{user}" /> (wrong)
  • Accessing prop without props or destructuring: user.name directly (wrong)
jsx
const user = { name: 'Alice', age: 30 };

// Wrong: passing object as string
function ParentWrong() {
  return <Child user="{user}" />; // This passes a string, not the object
}

// Correct: pass object inside curly braces
function ParentRight() {
  return <Child user={user} />;
}

// Wrong: child tries to access user.name directly
function ChildWrong() {
  // user is not defined here
  return <div>{user.name}</div>;
}

// Correct: access via props or destructuring
function ChildRight(props) {
  return <div>{props.user.name}</div>;
}
📊

Quick Reference

Remember these tips when passing objects as props:

  • Use curly braces {} to pass JavaScript objects as props.
  • Access props inside child components via props.propName or destructuring.
  • Do not pass objects as strings.
  • Props are read-only; do not modify them inside child components.

Key Takeaways

Pass objects as props using curly braces: <Component prop={object} />.
Access passed objects inside child components via props.prop or destructuring.
Never pass objects as strings; it breaks the data flow.
Props are read-only; avoid modifying them inside child components.
Use clear prop names to keep code readable and maintainable.