- Published on
Polymorphic component (with typescript)
React Polymorphic Components 구현
import React from 'react';
type TextOwnProps<E extends React.ElementType> = {
size?: 'sm' | 'md' | 'lg';
color?: 'primary' | 'secondary';
children: React.ReactNode;
as?: E;
};
type TextProps<E extends React.ElementType> = TextOwnProps<E> & Omit<React.ComponentProps<E>, keyof TextOwnProps<E>>;
export const Text = <E extends React.ElementType = 'div'>({ size, color, children, as, ...props }: TextProps<E>) => {
const Component = as || 'div';
return (
<Component {...props} className={`class-with-${size}-${color}`}>
{children}
</Component>
);
};
function App() {
return (
<div className="App">
<Text as="h1" size="lg">
Heading
</Text>
<Text as="p" size="md">
Paragraph
</Text>
<Text as="label" htmlFor="someId" size="sm" color="secondary">
Label
</Text>
</div>
);
}