Skip to content

Instantly share code, notes, and snippets.

@MR-Mostafa
Last active November 22, 2023 20:30
Show Gist options
  • Save MR-Mostafa/1ad15ad8045aeaffd9652cf98a736b8b to your computer and use it in GitHub Desktop.
Save MR-Mostafa/1ad15ad8045aeaffd9652cf98a736b8b to your computer and use it in GitHub Desktop.
Build strongly typed polymorphic components with React and TypeScript - Part 5
import * as React from 'react';
type Rainbow = "red" | "orange" | "yellow" | "green" | "blue" | "indigo" | "violet";
type ButtonProps<C extends React.ElementType> = {
as?: C;
color?: Rainbow | "black"; // 👈 look here
children: React.ReactNode;
} & React.ComponentPropsWithoutRef<C>;
export const Button = <C extends React.ElementType = 'button'>({
as,
children,
...otherProps
}: ButtonProps<C>) => {
const Component = as || 'button';
return <Component {...otherProps}>{children}</Component>;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment