What are polymorphic components in React
· Category: React
Short answer
A polymorphic component accepts an as prop that lets consumers change the underlying HTML element or component while keeping the same styling and behavior.
How it works
The component uses the as prop to determine what element to render, spreading the remaining props onto it. With TypeScript, you use generics to preserve prop types based on the chosen element.
Example
function Text({ as: Component = 'span', children, ...props }) {
return <Component {...props}>{children}</Component>;
}
// Usage
<Text as="h1">Heading</Text>
<Text as={Link} to="/">Link</Text>
Tips
- Polymorphism adds TypeScript complexity; libraries like
react-polymorphic-typeshelp. - Ensure ref forwarding works correctly with the dynamic component.