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; }
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 };
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}</>; }
Top comments (0)