So, you can assign a type of React.FC<PropsType> to a variable so that it is understood as a React Stateless Functional Component like so:
//Interface declaration
interface ButtonProps {
color: string,
text: string,
disabled?: boolean
}
// Function Component
let Button: React.FC<ButtonProps> = function(props){
return <div> ... </div> ;
}
However, I am having trouble understanding how to assign the same type to a FC built as a function declaration:
//Props interface already declared
function Button(props){
render <div> ... </div>;
}
I could assign the type to the props argument, and it would partly help since it would show what I expect to get from the caller (minus the children prop) but I don't think that would help with any intellisense from the calling context. I also have no idea what to set as the return type of the second example.
Thank you!
Not sure if you've found the answer by now, but adding a static type to a named function is nearly identical to how you did it in your initial example
Based on your example:
//Props interface already declared
function Button(props): React.ReactElement<Props> {
render <div> ... </div>;
}
// Or you could store the function in a named variable
const ButtonComponent: React.FunctionComponent<Props> = function Button(props): React.ReactElement<Props> {
render <div> ... </div>;
}
// Using shorthand type
const ButtonComponent: React.FC<Props> = function Button(props) {
render <div> ... </div>;
}
You can read up more on adding types to react components in this article
Note: Best practice is to use
React.FCinstead ofReact.SFCsince it's now deprecated in recent versions of React
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With