'Tailwind custom colors is not working in Next.js project [duplicate]
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?
Solution 1:[1]
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.
Solution 2:[2]
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>
Solution 3:[3]
you can pass the exact color in [ ]
<button class="bg-[#4AD7D1] hover:text-[#4AD7D1]">Submit</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hittingonme |
| Solution 2 | Dhaifallah |
| Solution 3 | Yilmaz |
