|
|
|
|
|
by 827a
327 days ago
|
|
My complaint with tailwind is that it doesn't do a good job of working well with components. E.g. if I have a component that wants to set a default background color for a button, but makes it customizable, I might think to do something like this? export function MyButton({ className }) {
return <button className={clsx("bg-red-500", className)} />
}
<MyButton className="bg-green-500" />
But that doesn't really work, because ultimately we've just provided both the bg-red-500 and bg-green-500 classes, and we're leaving it up to the precedence rules in the browser CSS engine (which I'm sure are consistent, but that feels like a no thanks from me)So instead I end up doing something like: export function MyButton({ bg = "bg-red-500" }) {
return <button className={bg} />
}
<MyButton className="bg-green-500" />
But that also feels unsatisfying, because while that prop is named 'bg' you could literally provide any tailwind class you want through it; there's no way to constrain it to only allow tailwind classes which are functionally interchangeable with bg-red-500.Anyone else run into this and have a nicer solution? |
|
The first is that my button will have variants, eg “primary, secondary, danger”. Those are a prop, the prop only accepts those values, and the value determines the classes applied
``` <button :class=“{ ‘bg-blue’: variant === ‘primary’, ‘bg-amber’: variant === ‘secondary’, ‘bg-red’: variant === ‘danger’, > ```
You could also have those variants just make a class=“variant-<value>” class and then use scoped styles to apply the proper classes - I’ve personally moved away from scoped styles in the last year.
Alternatively, such as in your case, I’d honestly lean towards !important:
``` <MyButton className=“!bg-green-500”> ```
And I know I know, !important bad!, and at least with Tailwind it’s obviously clear when someone has used !important. There’s no need to dig into the style files to track down the rule only to find someone sprinkled !importants everywhere.