The ComponentProps Type
Leverage the internal React ComponentProps type to handle dynamic component attributes.
We'll cover the following...
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.
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 are represented by React.ComponentPropsWithoutRef.
On line 4, the type of as is then passed to React.ComponentPropsWithoutRef.
Based on the type of as, represented by the generic C, ...