2

I'm having trouble following the current views on the best practice for typing functional React Native components in TypeScript. I find many posts and threads that seem to start with one view and then over time drift to another, without clear consensus.

Is there a current view on this? For example are any of the following preferred, or something else entirely?

// Version ONE (makes most "sense" to me)
const MyComponent = (props: MyComponentProps): JSX.Element => {
    return ( 
        //... some JSX
    )
}
// Version TWO (makes props a PropsWithChildren<MyComponentProps>?)
const MyComponent: FC<MyComponentProps> = (props) => {
    return (
        //... some JSX
    )
}
// Version THREE (what I have in older examples I've done, but I don't know why)
const MyComponent: FC<MyComponentProps> = (props): ReactElement => {
    return (
        //... some JSX
    )
}
2

1 Answer 1

-1

The most recent React Native template has had React.FC removed entirely. The recommended method in the new template is given as

const SometimesFancyButton = ({text, fancy}: SometimesFancyButtonProps) => {
    return fancy ? (<span className="fancy">{text}</span>) : text;
};

I.e. typing props but not the component return type, as an undefined component won't compile when imported (is how I interpreted the change). See discussion thread link thanks to @Benjamin

https://github.com/facebook/create-react-app/pull/8177


// Original (deprecated) answer below for context on comments

Version two is the most explicit and succinct. It tells Typescript that it expects certain props and returns a functional component, in one statement.

All three are valid and have no big downsides. Version one matches both functional and class components, so that's slightly less specific. Version three is redundant: since the component has already been typed, the return type on the function is unnecessary.

TL;DR: I prefer version two, but all are fine.

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

3 Comments

I had been using version two but was under the impression that FC was out of favor and had even been removed from project templates.
Also whatever these things are, they're not really functions (in the sense of Haskell or Flix) they are "functions" that take props as arguments and return (I think) a JSX.Element, which the first seems to capture best. I'm not really sure whether ReactElement is a better description of what's returned though.
@orome is correct, do not use React.FC in modern react apps. github.com/facebook/create-react-app/pull/8177

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.