Pass interface as props react

In React, you can pass an interface (also known as props) to a component.
Props are used to pass data or actions from a parent component to its child component.
This allows you to make your components reusable and maintain a clear separation of concerns.

To pass an interface as props to a React component, you need to define the interface in the parent component and explicitly pass it to the child component.
Here’s an example to illustrate this:

    
      import React from 'react';

      interface MyComponentProps {
        name: string;
        age: number;
      }

      const MyComponent: React.FC = (props) => {
        return (
          <div>
            <h2>Name: {props.name}</h2>
            <p>Age: {props.age}</p>
          </div>
        );
      }

      const ParentComponent = () => {
        return <MyComponent name="John" age={25} />;
      }

      export default ParentComponent;
    
  

In the example above, we define an interface named MyComponentProps in the parent component.
This interface requires two properties: name (a string) and age (a number).
We then create a functional component named MyComponent and specify its props type as MyComponentProps.
Inside MyComponent, we can access the passed props using the props object.
Finally, in the ParentComponent, we render MyComponent and pass the desired values for name and age as props.

Leave a comment