I have a React component called Buttons and as the name suggests, this component is used for all the buttons in my project. In order for this component to be completely dynamic, I decided to get the background color of the buttons from props(the background color is a tailwind class). Then I decided to put a hover class on the button so that when the mouse hovers over the button, the background color will increase by 100 units.
Button Component
export default function Button({ bg = "", children }) {
let bgColor = bg.split("-")
bgColor[2] = (+bgColor[2] + 100).toString()
let hoverEffect = "hover:" + bgColor.join("-")
return (
<button className={`${bg} ${hoverEffect} flex items-center justify-center gap-2 rounded-lg p-2 outline-none border-none transition-all cursor-pointer`}>
{children}
</button>
)
}
Using Button Component
<Button bg={"bg-sky-500"}>
submit
</Button>
For this, I implemented the JavaScript logic of this program, but finally, when this class is added to the component, nothing happens. What is the problem?
2
Answers
When generating Dynamic Classes, we need to add those classes in safelist in the tailwind.config.js file.
An example demonstrating the use of safelist:
Just verify the
bg
,hoverEffect
and make sure those are getting as you expected.If it’s not try splitting this line:
There is also a logical mistake here what if the
bg
is something like thisbg-blue-900
then your code will convert it tobg-blue-1000
in tailwind css it’s maximum is900
i guess!