Created
November 22, 2023 20:56
-
-
Save MR-Mostafa/5e19836e824deadb27d570cc321cb524 to your computer and use it in GitHub Desktop.
Build strongly typed polymorphic components with React and TypeScript - Part 8
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 * 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