create a react functional component with props in typescript

To create a functional component in React with props in TypeScript, you can follow the below steps -

  1. Define the interface for props (optional)
index.ts
interface Props {
  title: string;
  description: string;
}
60 chars
5 lines
  1. Define the functional component and pass the props as an argument of the component:
index.ts
import React from "react";

const MyComponent: React.FC<Props> = ({title, description}) => {
  return (
    <div>
      <h1>{title}</h1>
      <p>{description}</p>
    </div>
  );
}
182 chars
11 lines

Note: Here, we are using the React.FC type. It stands for FunctionComponent which specifies that this component is a function and accepts props of type Props.

  1. Finally, you can use this component by passing the props values:
index.ts
<MyComponent title="Hello" description="This is my first functional component with TypeScript." />
99 chars
2 lines

Here, we are passing the values for title and description props.

That's it! Now you have created a functional component in React with props in TypeScript.

gistlibby LogSnag