Tag
Render any element with `as`; its props stay correctly typed.
Usage
The props follow the element: href is typed on an a, and rejected on a section.
tsx
<Tag as="section" className="prose">
{children}
</Tag>
<Tag as="a" href="/about" rel="noreferrer">
About
</Tag>Building on Tag
TagProps<T, OwnProps> types a polymorphic component: the element's props plus your own. A prop you declare replaces the native one with the same name.
tsx
type ButtonOwnProps = {
active?: boolean;
onClick?: MouseEventHandler<HTMLElement>;
};
type ButtonProps<T extends ElementType = "button"> = TagProps<T, ButtonOwnProps>;Pass the remaining props through Tag.forward. It keeps the consumer's as, and takes care of the type assertion TypeScript needs here.
tsx
export const Card = <T extends ElementType = "div">({ className, children, ...rest }: CardProps<T>) => (
<Tag {...Tag.forward<T>(rest)} className={cn(cardBaseClassName, className)}>
{children}
</Tag>
);A default other than div
The second argument of Tag.forward is the element used when the consumer passes no as.
tsx
<Tag {...Tag.forward<T>(rest, "button")} onClick={handleClick} />Reference
| prop | type | default | |
|---|---|---|---|
as? | ElementType | "div" | the element or component to render |
…rest | props of as | — | typed against the chosen element |
Tag.forward
tsx
Tag.forward<T extends ElementType>(props: object, fallback?: ElementType): TagProps<T>;| prop | type | default | |
|---|---|---|---|
props | object | — | the remaining props, as or not |
fallback? | ElementType | — | the element to render when the consumer passes no as |