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

Estimated read time 2 min read

Passing an object as props to a component in React with TypeScript is similar to passing an object in JavaScript. However, we need to define the type of the object that we are passing as props. 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, { MyObjectType } from './MyComponent';

function App() {
  const myObject: MyObjectType = { 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 type MyObjectType, which is defined in MyComponent. Then, we 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, with its type. Here’s an example implementation of MyComponent that uses the passed myObject prop:

import React from 'react';

export type MyObjectType = {
  name: string;
  age: number;
  email: string;
}

type MyComponentProps = {
  myObject: MyObjectType;
}

function MyComponent(props: MyComponentProps) {
  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 define the type of the myObject prop using MyObjectType. 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