-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Helper to apply classNames to a dynamic element? #6
Comments
mgcrea
changed the title
Helper to apply className to a dynamic element?
Helper to apply classNames to a dynamic element?
Jan 26, 2023
The function MyCustomComponent(props) {
const {className} = props;
return (
<button>
{icon ? cloneElement(icon, {className}) : null}
{children}
</button>
);
}
const MyStyledCustomComponent = styled(MyCustomComponent, {
variants: {
size: {
xs: "w-4 h-4 -ml-0.5 mr-1",
sm: "w-4 h-4 -ml-0.5 mr-2",
md: "w-5 h-5 -ml-1 mr-2",
lg: "w-6 h-6 -ml-1 mr-3",
xl: "w-6 h-6 -ml-1 mr-3",
}
},
defaultVariants: {
size: "md",
},
}); Does that work? |
Or another option could be to create a wrapper component that passes the function IconWrapper(props: {
children: (className: string) => ReactElement,
className: string
}) {
const {children, className} = props;
<>
{children(className)}
</>
}
const StyledIcon = styled(IconWrapper, {
variants: {
size: {
xs: "w-4 h-4 -ml-0.5 mr-1",
sm: "w-4 h-4 -ml-0.5 mr-2",
md: "w-5 h-5 -ml-1 mr-2",
lg: "w-6 h-6 -ml-1 mr-3",
xl: "w-6 h-6 -ml-1 mr-3",
}
},
defaultVariants: {
size: "md",
},
}
function Button(props) {
const {icon, ...rest} = props;
return (
<button>
{icon ? (
<StyledIcon {...rest}>
{(className) => cloneElement(icon, {className})}
</StyledIcon>
: null}
{children}
</button>
)
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would be nice to have a className-like helper when you want to dynamically apply classes according to a variant config.
In my case, I'm playing with a basic
<Button />
component that would have anicon
prop that could receive anReactElement
:In this case I'd like to apply some size-based variants to the icon as well, something like:
That could be used this way:
Do you think this could be useful or would you do it differently (eg. nested styles, etc.)?
The text was updated successfully, but these errors were encountered: