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 ?
CodePudding user response:
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)
CodePudding user response:
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.Node; //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 }) => {