You can pass a single object that conforms to a specific interface as a prop to a child component. This approach allows you to encapsulate multiple related properties into a single prop, enhancing code readability and maintainability.
Defining the Interface:
// types.ts
export interface User {
name: string;
age: number;
email: string;
}
Parent Component:
// ParentComponent.tsx
import React from 'react';
import { User } from './types';
import ChildComponent from './ChildComponent';
const ParentComponent: React.FC = () => {
const user: User = {
name: 'John Doe',
age: 30,
email: 'john.doe@example.com',
};
return <ChildComponent user={user} />;
};
export default ParentComponent;
Child Component:
// ChildComponent.tsx
import React from 'react';
import { User } from './types';
interface ChildComponentProps {
user: User;
}
const ChildComponent: React.FC<ChildComponentProps> = ({ user }) => {
return (
<div>
<h1>{user.name}</h1>
<p>Age: {user.age}</p>
<p>Email: {user.email}</p>
</div>
);
};
export default ChildComponent;