skip to Main Content

I have the following component:

const MyComponent: React.FC = function(){
  return "hello world"
}

It’s correct, and it’s not false, however, typescript is complaining that this is not correct because the return type is a string, it thinks that it should be a JSX element.

Then what is the correct type to use here?

I want to simply define a component, so it will still understand the types of the parameters, so the props and the ref,

so it’s still a component,

I don’t want to write

: string as the return type simply because it’s not totally correct, it’s not a normal function it’s a component.

But I think that the implementation of the FC type is either wrong or that I should use another type.

Which type defines a component?

2

Answers


  1. In general it is discouraged to use React.FunctionComponent or it’s shorthand React.FC. I have found that it ends up causing friction and churn for very little gain. You can read more about it here, but here’s the lowdown:

    Pros of using React.FC:

    • more explicit
    • it provides typechecking and autocomplete for static properties like displayName, propTypes, and defaultProps.
    • (pre v18) automatically includes children in the props… which is not always desirable

    Cons of using React.FC:

    • extremely verbose, hard to read, "gets in your way" when you just want to make a component
    • (pre v18) automatically includes children in the props, which is not always desirable

    I stopped using it a couple years ago when they initially discouraged it, and I couldn’t be happier. You literally just write functions as you normally would and TS will infer the return type. I generally define my props separately like this:

    type MyComponentProps =  {...};
    
    const MyComponent = ({ ... }: MyComponentProps) => {
       ...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search