DEV Community

skube
skube

Posted on • Edited on

1

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post →

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay