Skip to content

Instantly share code, notes, and snippets.

@MR-Mostafa
Created November 22, 2023 20:56
Show Gist options
  • Save MR-Mostafa/5e19836e824deadb27d570cc321cb524 to your computer and use it in GitHub Desktop.
Save MR-Mostafa/5e19836e824deadb27d570cc321cb524 to your computer and use it in GitHub Desktop.
Build strongly typed polymorphic components with React and TypeScript - Part 8
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";
};
type Props <C extends React.ElementType> =
React.PropsWithChildren<ButtonProps<C>> &
Omit<React.ComponentPropsWithoutRef<C>, keyof ButtonProps<C>>;
export const Button = <C extends React.ElementType = 'button'>({
as,
children,
color, // 👈 look here
...otherProps
}: Props<C>) => {
const Component = as || 'button';
// را با استایل‌های وارد شده در یک آبجکت ذخیره می‌کنیم color مقدار ورودی
const styles = color ? { style: {...otherProps.style, color } } : {style: {...otherProps.style} };
// در نهایت به کامپوننت پاس می‌دهیم
return <Component {...otherProps} {...styles}>{children}</Component>;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment