-
Notifications
You must be signed in to change notification settings - Fork 21
How to extract props from styled component #64
Unanswered
dominictobias
asked this question in
Q&A
Taking the example:
const Button = styled('button', { base: { borderRadius: 6, }, variants: { color: { neutral: { background: 'whitesmoke' }, brand: { background: 'blueviolet' }, accent: { background: 'slateblue' }, }, size: { small: { padding: 12 }, medium: { padding: 16 }, large: { padding: 24 }, }, rounded: { true: { borderRadius: 999 }, }, }, compoundVariants: [ { variants: { color: 'neutral', size: 'large', }, style: { background: 'ghostwhite', }, }, ], defaultVariants: { color: 'accent', size: 'medium', }, });
How can we extract the props rounded, color, and size into a type, so that we could mix in other props that our component might want? (In the case that we have a wrapping component which performs additional logic/rendering, but we still want the end user to get these props, which will will pass through)
I thought typeof but I'm getting a confusing error that no types overlap:
interface ButtonProps extends StyledButtonProps { loading?: boolean // for example } export default function Button(attrs: ButtonProps) { return <StyledButton {...attrs} /> } function Test() { return <Button rounded /> } const StyledButton = styled('button', { base: { appearance: 'none', padding: '0.5em 1em', border: 'none', fontFamily: 'inherit', }, variants: { hue: { neutral: { background: 'whitesmoke' }, accent: { background: 'slateblue' }, }, rounded: { true: { borderRadius: 4 }, }, }, compoundVariants: [ { variants: { hue: 'neutral', rounded: true, }, style: { background: 'ghostwhite' }, }, ], defaultVariants: { hue: 'accent', rounded: true, }, }) type StyledButtonProps = typeof StyledButton
Type '{ loading?: boolean | undefined; variants: ("hue" | "rounded")[]; selector: RuntimeFn<{ hue: { neutral: { background: "whitesmoke"; }; accent: { background: "slateblue"; }; }; rounded: { true: { borderRadius: number; }; }; }>; }' has no properties in common with type 'IntrinsicAttributes & ButtonHTMLAttributes<HTMLButtonElement> & VariantSelection<{ hue: { neutral: { background: "whitesmoke"; }; accent: { ...; }; }; rounded: { ...; }; }> & { ...; } & { ...; }'.ts(2559)
All reactions
Replies: 1 comment
To get type of props for any React component (not only when using macaron-css) you can use React.ComponentProps type:
type StyledButtonProps = React.ComponentProps<typeof StyledButton>
then, to get type of each variant (as you asked for in your question) you can use:
type ColorProp = StyledButtonProps['color'] // ^? type ColorProp = "neutral" | "brand" | "accent" | undefined type RoundedProp = StyledButtonProps['rounded'] // ^? type RoundedProp = boolean | undefined
All reactions
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment