5

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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to add the props interface in the first example? And why the latter integrates better with the ecosystem?
That's what I meant by integrates better, you'll be able to properly leverage types and intellisense for your component props and state. I'm not aware of a way to make that work with the first example so in reality it has limited use cases. Why is it that you're trying to avoid using arrow functions?

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.