Reputation: 2627
This works fine:
import React, { FunctionComponent } from "react";
const Counter: FunctionComponent = () => <div>hello from Counter</div>;
export default Counter;
This has compile error:
import React, { FunctionComponent } from "react";
function Counter1(): FunctionComponent {
return <div>hello from Counter1</div>;
}
export default Counter1;
The error says:
Type 'Element' is not assignable to type 'FunctionComponent<{}>'.
Type 'Element' provides no match for the signature '(props: { children?: ReactNode; }, context?: any): ReactElement ReactElement Component)>) | (new (props: any) => Component)>'.ts(2322)
How to write functional component with FunctionComponent type using "function" syntax?
Upvotes: 6
Views: 12256
Reputation: 3542
A react functional component is function returning a ReactElement
(this is what several libraries returns in their TypeScript definition, by example react-router-dom
):
import React, { ReactElement } from 'react';
function Counter1(): ReactElement {
return <div>hello from Counter1</div>;
}
Upvotes: 0
Reputation: 14318
You can use an interface with the same name as the function.
interface Counter extends FunctionComponent {}
function Counter() {
return <div>hello from Counter1</div>;
}
Upvotes: 1
Reputation: 18541
In
const Counter: FunctionComponent = () => <div>hello from Counter</div>;
Counter
is of type FunctionComponent
. That is the desired behavior. But in:
function Counter(): FunctionComponent {
return <div>hello from Counter1</div>;
}
Counter
's type is a function that returns a FunctionComponent
which is not what you want, and does not fit the function definition.
If you absolutely want to use function
, you can write it like that:
const Counter: FunctionComponent = function() {
return <div>hello from Counter1</div>;
}
Upvotes: 9