3

The custom colors configured in tailwind.config.js is not working, when I assigned to a variable and use it as shown below.

where button.colour = "custom-blue" ( Colour data is fetched from the cms and can be set in cms )

<button class="inline-block px-6 py-2.5 bg-${button.colour} text-custom-dark-blue font-medium text-sm leading-tight rounded shadow-md hover:bg-white hover:border-2 border-custom-blue hover:text-${button.colour}">Submit</button>

But the below code works perfectly fine.

<button class="inline-block px-6 py-2.5 bg-custom-blue text-custom-dark-blue font-medium text-sm leading-tight rounded shadow-md hover:bg-white hover:border-2 border-custom-blue hover:text-custom-blue">Submit</button>

tailwind.config.js file:

module.exports = {
  content: [
    './pages/**/*.{js,ts,jsx,tsx}',
    './components/**/*.{js,ts,jsx,tsx}'
  ]
  ,
  theme: {
    extend: {
      colors: {
        'custom-blue':'#4AD7D1',
       },
    },
  
  },
  plugins: [],
  important: true
}

How to resolve this issue?

  • The class purger does not recognize that you are using the class so it gets removed in the build. A work around this is to make a map of values to tailwind classes – kelsny Mar 21 '22 at 13:19

2 Answers2

2

Under this section in the docs:

As outlined in Class detection in-depth, Tailwind doesn’t actually run your source code and won’t detect dynamically constructed class names.

And as my comment mentions, Tailwind's class purger (PurgeCSS) just sees if classes are included in your source code and keeps them if they are. It does not include dynamically created classes like bg-${button.color}.

The work around I suggested would go something like this:

const backgroundClassMap = {
    "custom-blue": "bg-custom-blue",
};

...

<button class={`some other classes ${backgroundClassMap[button.color]}`}>

Because with this method, the class bg-custom-blue is indeed present and being used, so it won't be excluded from the build.

kelsny
  • 23,009
  • 3
  • 19
  • 48
-1

I'm not quite sure why would you want to do this, but here is how: First, define a button object :

const button={
      colour: "custom-blue" 
}

Then, you can use it like this:

<button className={`bg-${button.colour} ...`}>
        Submit
</button>
Dhaifallah
  • 1,437
  • 1
  • 5
  • 19
  • This won't work with Tailwind v3+ and this video from Tailwind shows how to make this work, and what this won't work https://youtu.be/waoOK5s9ypc?t=315 – MiFiHiBye Jun 20 '22 at 17:42