Issue
while creating a react component i can define type in these two methods, but i want to know the difference between these two,
Method 1
const MyComponent:React.FC<IProps> = () => (<></>)
interface IProps {
Title: string
}
Method 2
const MyComponent:React.FC = () => (<></>)
MyComponent.propTypes = {
Title: string
}
what is the difference between these two type defining.
while iam trying i got a error,
In method one i tried to add
const MyComponent:React.FC<IProps> = () => (<></>)
interface IProps {
Title: React.FC
}
but, while adding the same thing to the proptype it got error
const MyComponent:React.FC = () => (<></>)
MyComponent.propTypes = {
Title: React.FC
}
Solution
propTypes
has nothing to do with TypeScript; it's a run-time/lint-time check that React and certain React tools know of.
The allowed prop types are separate from the TypeScript type system, which is why using React.FC
in propTypes
is an error.
(MyComponent.propTypes = {Title: string}
is also incorrect, but doesn't cause an error – just that the actual propTypes is {Title: undefined}
, which doesn't help.)
Additionally, you don't want to use React.FC
unless your component accepts the children
prop (and even so, you could just use React.PropsWithChildren<IProps>
).
IOW,
interface Props {
title: string;
}
function MyComponent({title}: Props) {
return <h1>{title}</h1>;
}
is enough and gives you compile-time type checking for MyComponent
.
Answered By - AKX
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.