How to Pass an Object as Props to a Component in React?

Estimated read time 2 min read

Passing an object as props to a component in React is quite simple. You can pass an object as a prop by passing it as a value to the prop name when rendering the component. Here’s an example:

Assuming we have a component called MyComponent that accepts an object as a prop named myObject, we can pass an object to it in the following way:

import React from 'react';
import MyComponent from './MyComponent';

function App() {
  const myObject = { name: 'John', age: 30, email: 'john@example.com' };
  
  return (
    <div>
      <MyComponent myObject={myObject} />
    </div>
  );
}

In the code above, we define an object myObject with some properties, and then pass it as a prop to the MyComponent component. The prop name myObject is defined inside the opening tag of MyComponent.

In the receiving component, we can access the object using the props parameter. Here’s an example implementation of MyComponent that uses the passed myObject prop:

import React from 'react';

function MyComponent(props) {
  return (
    <div>
      <p>Name: {props.myObject.name}</p>
      <p>Age: {props.myObject.age}</p>
      <p>Email: {props.myObject.email}</p>
    </div>
  );
}

export default MyComponent;

In the MyComponent component, we can access the myObject prop using props.myObject. We can then access the properties of the object using the dot notation, like props.myObject.name, props.myObject.age, and props.myObject.email.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply