masiyik879
masiyik879

Reputation: 351

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

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..

Upvotes: 0

Views: 1664

Answers (2)

AmerllicA
AmerllicA

Reputation: 32522

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}
    </>
  );
};

Upvotes: -1

gqstav
gqstav

Reputation: 2072

  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}
    </>
  );
};

Upvotes: 4

Related Questions