Last active
March 20, 2024 13:21
-
-
Save mateusvahl/a3e1b351cada6c2e2daf35482ed1eded to your computer and use it in GitHub Desktop.
React / Typescript Dynamic tag with intellisense autocomplete
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 { ReactNode, ElementType, ComponentPropsWithoutRef } from "react"; | |
export type Prefer<P, T> = P & Omit<T, keyof P>; | |
export type ElementPropsWithoutRef<T extends ElementType> = Pick< | |
ComponentPropsWithoutRef<T>, | |
keyof ComponentPropsWithoutRef<T> | |
>; | |
export type OverwritableType<OwnProps, Type extends ElementType> = Prefer< | |
OwnProps, | |
ElementPropsWithoutRef<Type> | |
>; | |
interface Props<T> { | |
as?: T; | |
children?: ReactNode; | |
} | |
// 'button' is a default value | |
function Box<T extends ElementType = "button">({ | |
as, | |
children, | |
...rest | |
}: OverwritableType<Props<T>, T>) { | |
const Tag: ElementType = as; | |
return ( | |
<Tag {...rest}> | |
{children} | |
</Tag> | |
); | |
} | |
export default Box; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment