circuit

How to Use React.FC Children Prop in React 18 with TypeScript

How to deal with the new React 18 React.FC type and the children prop for TypeScript




Article image

Using the new React.FC component type on your already existing project you might be ending with the following error:

Property 'children' does not exist on type <YourCustomTypeProps>

This is because the type signature has changed in the recent version of React.

Why did the FC signature change?

The children prop was removed from React.FunctionComponent (React.FC) so you have to declare it explicitly in your component properties.

TLDR; it prevents bugs like this:

const ComponentWithNoChildren: React.FC = () => <>Hello</>;
...
<ComponentWithNoChildren>
   // passing children is wrong since component does not accept any
   <UnusedChildrenSinceComponentHasNoChildren />
</ComponentWithNoChildren>

This way you can be certain that the component you're using is handling children, even improving your codebase and quality.

How to play with React.FC and children in React 18+

Before

In the previous version the children prop was already defined as an optional property in React.FC type.

import * as React from 'react';

type Props = {};
const Component: React.FC<Props> = ({children}) => {...}

After

In the recent version, this has been removed. Now, you have to specify it explicitly depending on your need. It can be either optional or required, it's up to your own logic.

import * as React from 'react';

type Props = {
  children?: React.ReactNode
};
const Component: React.FC<Props> = ({children}) => {...}

But what if I want to keep the old React.FC with children behavior?

You can override react types by creating a custom type definition file. It can be either your already global existing one, or you can make a new one named arbitrary react.d.ts which is in the scope of your TypeScript compiler.

The following definition would revert the type to @types/react v17:

import * as React from '@types/react';
declare module 'react' {
  interface FunctionComponent<P = {}> {
    (props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;
  }
}

Now let's enjoy strong type definition!




Continue Learning