0_CBjisl422hUyLxiG

The TypeScript type of React children

The correct type is React.ReactNode.

Say you have a component

function Code({ children }: { children: any }) {
  return (
    <code className="relative select-all rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold">
      {children}
    </code>
  );
}

The type of children is not string, JSX.Element, nor JSX.Element[]. The most ergonomic type to use is React.ReactNode.

function Code({ children }: { children: React.ReactNode }) {
  return (
    <code className="relative select-all rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold">
      {children}
    </code>
  );
}

It's a simple problem, with a simple solution but it can be infuriating looking for the right type that accepts all kinds of inputs.

That's why it's in the first sentence of this post 😃