'Why "he" does not write React.FC on each function?
I learn typescript, and I dont understand why he write in the first Function React.FC and in other function he does not write "React.FC". Why?
exp:
...
const Login: React.FC<Props> = ({ signIn }) => {
const Add = (id: number) => {
...
};
return (
<div>
<p>Hello</p>
</div>
)
};
Why I dont write React.FC in Add function ?
Solution 1:[1]
Combining with Typescript I actually use FC
only if I want to pass and extract children
from props because it is the best way to type them. If we use your example:
Without children it can be like:
interface Props {
signIn: string;
}
const Login = ({ signIn }: Props) => {
With children you can still do it the same way:
interface Props {
signIn: string;
children: React.ReactNode; //or something similar, there are few options
}
const Login = ({ signIn, children }: Props) => {
or you can use FC
here and skip children in your Props
interface:
interface Props {
signIn: string;
}
const Login: React.FC<Props> = ({ signIn, children }) => {
Solution 2:[2]
React.FC
is (and is only) used to enforce the types for a React functional component - a function that takes in props (a single argument, which is an object) and returns a JSX.Element
.
Add
is not a React component, but a plain function. There's no information on how it's used, but because its argument is (id: number)
, it's clearly not a component - so it shouldn't be typed as React.FC
.
(You don't even need React.FC
on components anyway - it's just a convention that some prefer)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | CertainPerformance |