Search⌘ K
AI Features

The ComponentProps Type

Explore how to leverage React.ComponentPropsWithoutRef and TypeScript generics to create polymorphic React components that correctly enforce valid HTML attributes and catch errors during development.

In order to handle relevant attribute polymorphic props, what we need to do is to leverage the React.ComponentPropsWithoutRef type, as shown below.

TypeScript 3.3.4
type PolymorphicTextProps<C extends React.ElementType> = {
as?: C;
children: React.ReactNode;
} & React.ComponentPropsWithoutRef<C>;
export const PolymorphicText = <C extends React.ElementType>({
as,
children,
}: PolymorphicTextProps<C>) => {
const Component = as || "span";
return <Component>{children}</Component>;
};

Note that we’re introducing an intersection here. Essentially, we’re saying the type of PolymorphicTextProps is an object type containing as and ...