...
/Handling Default Values for the Polymorphic Prop
Handling Default Values for the Polymorphic Prop
Learn to pass a default generic value and leverage that in a polymorphic component.
We'll cover the following...
Let's consider our current solution, and pay attention to where a default element is provided if the as
prop is omitted.
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,...restProps}: PolymorphicTextProps<C>) => {const Component = as || "span";return <Component {...restProps}>{children}</Component>;};
Let's look at line 11 above. If the as
prop is not provided, it will default to the string span
.