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.
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>
)
}
<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?
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:
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
safelist: [
{
pattern: /bg-(.*)-(.*)/,
variants: ['hover'],
},
],
theme: {
extend: {},
},
plugins: [],
}