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
I would use
React.ReactNode
:https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCmATzCTgAUcwBnOAXjgG8K4+4A9ALgA6MRQC+FCkgAekWHEwBXAHYZgEVXACy1AMK5IqpKpgAKMMxYAuRtYCUd5OhgiXGAHIQAJvR7k-HBEMMpQ2vgAEkgANjEQcADu0DE+AIRk5BJAA
In general it is discouraged to use
React.FunctionComponent
or it’s shorthandReact.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
:children
in the props… which is not always desirableCons of using
React.FC
:children
in the props, which is not always desirableI 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: