How to pass props to a functional React component using typescript

Post author: Adam VanBuskirk
Adam VanBuskirk
6/18/23 in
Tech
ReactTypeScript

In React with TypeScript, you can pass props to a functional component by specifying the prop types using TypeScript’s type annotations. Here’s an example:

import React from 'react';

// Define the prop types for the component
interface MyComponentProps {
  name: string;
  age: number;
}

// Define the functional component
const MyComponent: React.FC<MyComponentProps> = ({ name, age }) => {
  return (
    <div>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
    </div>
  );
};

// Usage of the component
const App: React.FC = () => {
  return <MyComponent name="John" age={25} />;
};

In the above example, we define the prop types for MyComponent using an interface MyComponentProps. The interface specifies that name prop should be a string and age prop should be a number.

Then, when declaring the functional component MyComponent, we pass MyComponentProps as a generic type argument to React.FC (FunctionComponent) to specify the expected prop types.

Finally, in the usage of MyComponent, we pass the props name and age as attributes with their respective values.

By using TypeScript with React in this way, you can ensure that the correct props are passed to your components and catch any type errors during development.

You can also use the below style.

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

function MyComponent(props: Props) {
    return (<div>Hello World {props.name}. You're age is {props.age}</div>);
}

export default MyComponent;

Sign up today for our weekly newsletter about AI, SEO, and Entrepreneurship

Leave a Reply

Your email address will not be published. Required fields are marked *


Read Next




© 2024 Menyu LLC