logoalt Hacker News

9devtoday at 9:36 AM1 replyview on HN

That is kind of my point, though—you don't need tailwind-merge, really. There are two cases it solves:

One, adding classes from the outside to an encapsulated component with its own, internal classes, to make sure the outside-applied classes take priority. Either use the !important modifier on them (`ms-auto!`), put the components into a container div with the classes for layout concerns, or even better: Figure out why you need to make styling changes to a component that cannot be expressed via props. I would generally recommend components to not have outside-element styling like margins in them anyway, which most often fights with positioning later.

Two, merging prop-derived styling with base styles - for example for a `size: 'sm'|'lg'` prop. It's tempting to just use tailwind-merge here:

  const classList = tailwindMerge(
    'p-4',
    size == 'sm' && 'p-2',
    size == 'lg' && 'p-6',
  );
But that isn't necessary at all: The better alternative would be to use data attributes for visual concerns and built-in or aria attributes for interaction states. There are almost always element attributes that can represent what you want to have correctly, and data- where there are not. Then, you can just add a class accordingly:

  <span 
    class="p-4 data-[size=sm]:p-2 data-[size=lg]:p-6 data-active:font-bold"
    data-size={size}
    data-active={active}
  />
And you'll end up with easier to maintain components that derive their styles from the CSS cascade alone.

Replies

francislavoietoday at 10:07 AM

I would reach for class-variance-authority (aka cva) instead for stuff like a size prop, it declaratively solves that.

show 1 reply