6

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?

0

3 Answers 3

9

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>;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use an interface with the same name as the function.

interface Counter extends FunctionComponent {}
function Counter() {
  return <div>hello from Counter1</div>;
}

Comments

0

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>;
}

2 Comments

Could you please improve this answer by adding a few words of explanation?
@MikeSzyndel: A react functional component is function returning a ReactElement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.