Reputation: 175
Currently I have this React component typed as such:
import React, { FunctionComponent } from "react";
const HelloWorld : FunctionComponent = () => {
return (
<div>
Hello
</div>
);
}
export default HelloWorld;
I would not like to use arrow functions and write my component like so:
import React, { FunctionComponent } from "react";
function HelloWorld() {
return (
<div>
Hello
</div>
);
}
export default HelloWorld;
Is it possible to type normal functions as FunctionComponent
?
Upvotes: 5
Views: 4517
Reputation: 21147
The FunctionComponent
type basically boils down to a function that receives props and returns a ReactElement
:
(props: PropsWithChildren<P>, context?: any): ReactElement | null;
So one option would be to type your non-arrow function accordingly:
function HelloWorld(): ReactElement {
return (
<div>
Hello
</div>
);
}
The other option (which integrates better with the rest of the TS React ecosystem) is to store your function in a named variable:
interface SomeProps {
someValue: number
}
const HelloWorld: FunctionComponent<SomeProps> = function HelloWorld({ someValue }) {
return <div>Hi {someValue}</div>
}
Overall though I would recommend that you just use arrow functions as they offer benefits especially when it comes to JS scopes and the this
reference.
Upvotes: 5