How to override previous classes with next classes in tailwind?

Viewed 467

I'm using React + Tailwind. Consider this code:

// in Styles.js module
export const Button = "uppercase h-12 flex justify-center items-center bg-purple-700 ";

// in Pricing.js module
import { Button } from './Styles';

<button className={Button + " bg-green-400"}>Special offer</button>

I expect the background of special offer button to become green, but it does not.

The point is, when we concatenate classes in tailwind, the latter classes won't override the previous classes. This is far from the cascading nature of CSS.

How can I override previous classes in concatenations?

2 Answers

You have to use template literals, like this:

//const bg = "bg-green-100";

//<div className={`grid grid-cols-3 gap-4 p-24 h-auto ${bg}`}>

Please note that template literals here must be inside a {} because it is JavaScript.

For future interested ones.

In my case template literals do not made the difference (referring to the other answer), in fact the code was already with template strings, but just inserted the class in the html tree as an overwrited one, prioritizing the preexisting one in the component. At the end, I think, it is just a syntax sugar.

I found a workaround by specifying de breakpoint like this:

export const Button = "...previusClasses md:bg-purple-700 ";

Obviously just put the breakpoints that suits you.

Hope it help someone someday.

Related