0

What is correct way how to create functional component in react using typescript ?

  1. Should I use interface or type for props?
  2. Should I use React.FC or React.FunctionComponent?
  3. How can I validate props using eslint?

Right now, my typically components looks like:

interface IProps {
  color: string;
}

const Example = (props: IProps) => {
  const { color } = props;

  return (
    <>
      {color}
    </>
  );
};

I am not sure if it best way...

Also I dont know how to validate props usingeslint`, for example when I want to pass down color as a number..

2
  • 1
    React.FC and React.FunctionComponent are the same. Commented May 3, 2020 at 15:00
  • 1
    Your code is almost there. You just need to change const Example = (props: IProps) => { to const Example: React.FC<IProps> = (props) => {. In addition, your interface is fine! Commented May 3, 2020 at 15:13

2 Answers 2

4
  1. Both are used frequently in the community. I prefer type as I find it easier to use, but you can read here https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#3.10 and make your own opinion.
  2. React.FC is shorthand for React.FunctionComponent
  3. props will be validated by the TypeScript static analysis.

I found this pattern helpful when starting with function components:

type Props {
  color: string;
}

const Example: React.FC<Props> = ({color}: Props) => {

  return (
    <>
      {color}
    </>
  );
};
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, is there any option how to run only TypeScript static analysis from command line? I would like to run it before commit after eslint check. Or do you mean TSLINT?
If you bootstrap your project with npx create-react-app my-app --template typescript it'll already be there for you by default and if you break the rules of TypeScript it'll complain while running npm start. For running it from command line, see e.g. here stackoverflow.com/questions/33535879/…
-1

By the Maximilian Schwarzmüller guides the best approach is:

import React from 'react';
import type { FC } from  'react';

interface SampleProps {
  color: string;
}

const Sample: FC<SampleProps> = ({ color }) => {
  return (
    <>
      {color}
    </>
  );
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.