Last active
February 6, 2025 07:44
-
-
Save kripod/4434e7cecfdecee160026aee49ea6ee8 to your computer and use it in GitHub Desktop.
Superseded by https://www.kripod.dev/blog/behind-the-as-prop-polymorphism-done-well/ – Polymorphic `as` prop for React components with TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React from 'react'; | |
| // Source: https://github.com/emotion-js/emotion/blob/master/packages/styled-base/types/helper.d.ts | |
| export type PropsOf< | |
| // eslint-disable-next-line @typescript-eslint/no-explicit-any | |
| C extends keyof JSX.IntrinsicElements | React.JSXElementConstructor<any> | |
| > = JSX.LibraryManagedAttributes<C, React.ComponentPropsWithoutRef<C>>; | |
| export interface BoxOwnProps<C extends React.ElementType = React.ElementType> { | |
| as?: C; | |
| } | |
| export type BoxProps<C extends React.ElementType> = BoxOwnProps<C> & PropsOf<C>; | |
| type AsProp<C> = | |
| | keyof JSX.IntrinsicElements | |
| | React.ComponentType<C extends React.ComponentType<infer P> ? P : never>; | |
| export function BoxWithoutRef<C extends AsProp<C> = 'div'>({ | |
| as, | |
| ...restProps | |
| }: BoxProps<C>): JSX.Element { | |
| const Element: React.ElementType = as || 'div'; | |
| return <Element {...restProps} />; | |
| } | |
| export const Box = React.forwardRef( | |
| ( | |
| { as: Element = 'div', ...restProps }: BoxOwnProps, | |
| ref: React.Ref<Element>, | |
| ) => { | |
| return <Element ref={ref} {...restProps} />; | |
| }, | |
| ) as <T, C extends AsProp<C> = 'div'>( | |
| props: BoxProps<C> & React.RefAttributes<T>, | |
| ) => JSX.Element; |
Hmmm... I'm getting an error that Box.displayName is not specified, but when I add it, then TypeScript complains. Same goes when I add PropTypes...
How can I limit as to specific elements like h1 | h2 | h3 | P only?
Author
@vfshera you may swap extends React.ElementType instances for extends "h1" | "h2" | "h3" | "p".
Author
@vfshera I recently wrote an article about polymorphism in React, which embraces narrowing the set of built-in elements endorsed as a performance improvement.
thanks checking it out
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great