0 day streak
javascript / expert
Snippet

Polymorphic Components with TypeScript Generics

Polymorphic components allow a single React component to render as different HTML elements or other components while maintaining full type safety for the specific attributes of that element.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
type BoxProps<T extends React.ElementType> = {
as?: T;
children: React.ReactNode;
} & React.ComponentPropsWithoutRef<T>;
function Box<T extends React.ElementType = 'div'>({ as, ...props }: BoxProps<T>) {
const Component = as || 'div';
return <Component {...props} />;
}
react
Breakdown
1
type BoxProps<T extends React.ElementType>
Defines a generic type that accepts any valid React element type (like 'div', 'button', or a custom component).
2
as?: T;
The optional 'as' prop determines the underlying element to be rendered.
3
& React.ComponentPropsWithoutRef<T>
Uses intersection types to pull in all valid HTML attributes for the element type provided in T.