DEV Community

skube
skube

Posted on • Edited on

Typing Function Components with Children

Typing Function Components while using children has changed since React 18+.

Previous to React 18, FC included children.

Now, the types for FC do not include children.

// @types/react
type FC<P = {}> = FunctionComponent<P>;

interface FunctionComponent<P = {}> {
  (props: P, context?: any): ReactElement<any, any> | null;
  propTypes?: WeakValidationMap<P> | undefined;
  contextTypes?: ValidationMap<any> | undefined;
  defaultProps?: Partial<P> | undefined;
  displayName?: string | undefined;
}
Enter fullscreen mode Exit fullscreen mode

Instead, one can use PropsWithChilden as a shortcut to specifying children type for your Function.

// @types/react
type PropsWithChildren<P = unknown> = P & { children?: ReactNode | undefined };
Enter fullscreen mode Exit fullscreen mode

Examples

import { FC, PropsWithChildren, ReactNode } from 'react';

// Arrow function: explicitly typing children
type PropsA = {
  children: ReactNode;
};
export const A = ({ children }: PropsA): JSX.Element => <>{children}</>;

// Arrow function (shortcut)
type PropsB = FC<PropsWithChildren<Record<string, unknown>>>;
export const B: PropsB = ({ children }) => <>{children}</>;

// Named function (explicitly)
type PropsC = {
  children: ReactNode;
};
export function C({ children }: PropsC): JSX.Element {
  return <>{children}</>;
}

// Named function (shortcut)
export function D({
  children,
}: PropsWithChildren<Record<string, unknown>>): JSX.Element {
  return <>{children}</>;
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)