skip to Main Content

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


  1. 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: [],
    }
    Login or Signup to reply.
  2. Just verify the bg,hoverEffect and make sure those are getting as you expected.

    If it’s not try splitting this line:

    bgColor[2] = (+bgColor[2] + 100);
    bgColor[2] = bgColor[2].toString()
    

    There is also a logical mistake here what if the bg is something like this bg-blue-900 then your code will convert it to bg-blue-1000 in tailwind css it’s maximum is 900 i guess!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search