create a react functional component in typescript

To create a React functional component in TypeScript, you first need to create a TypeScript file with a .tsx extension.

import React from 'react';

type Props = {
   name: string,
   age: number
};

const MyComponent: React.FC<Props> = ({ name, age }) => {
   return (
      <div>
         <h1>{name}</h1>
         <p>Age: {age}</p>
      </div>
   );
}

export default MyComponent;
263 chars
18 lines

In this example, we imported React and defined a type for the component props. We then defined a functional component called MyComponent that receives the props object as an argument, destructures it to get the name and age properties, and returns JSX.

Note that we are using the React.FC type to define the component type, which is a generic type that takes the props interface as a parameter.

Finally, we export the component as the default export of the module so that we can import and use it in other parts of our application.

gistlibby LogSnag