The ComponentProps Type
Leverage the internal React ComponentProps type to handle dynamic component attributes.
We'll cover the following...
In order to handle relevant attribute polymorphic props, what we need to do is to leverage the React.ComponentPropsWithoutRef
type, as shown below.
Press + to interact
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 children
, and some other types ...