1

I have latest nextjs + tailwind. Here is my tailwind config:

module.exports = {
    mode: "jit",
    content: [
        "./pages/**/*.{js,ts,jsx,tsx}",
        "./components/**/*.{js,ts,jsx,tsx}",
    ],
    theme: {
        extend: {},
    },
    plugins: [],
};

Inside components folder I have Test.js component with content:

const colors = {
    orange: "bg-orange-100",
    blue: "bg-blue-100",
};

export default function Header() {
    function HeaderButton(props) {
        return <div className={`bg-red hover:${colors[props.color]}`}></div>;
    }
    return <HeaderButton color="orange">Test</HeaderButton>
}

bg-red class is present, but on hover I get class bg-orange-100 and it's purged from result css so no result. What could be wrong?


So I found the problem is exactly in hover. If I just add class name this way it works okay. Doesn't work for modificators like hover etc.

Max Frai
  • 61,946
  • 78
  • 197
  • 306
  • Tailwind's postcss removes any class that are not being used. This could be a limitation if tailwind doesn't allow dynamic class names – ahsan Apr 15 '22 at 15:50
  • @AhsanKhan I thought that mentiong class in js variable like that is a "hack" that tells postcss to not remove it becasuse it's used? – Max Frai Apr 15 '22 at 15:51
  • I just looked it up, tailwind doesn't recommend doing this. check: https://stackoverflow.com/questions/69687530/dynamically-build-classnames-in-tailwindcss – ahsan Apr 15 '22 at 15:51
  • 1
    maybe try adding it to js variable along with `hover:` – ahsan Apr 15 '22 at 15:52

1 Answers1

2

as tailwind documentation mentioned https://v2.tailwindcss.com/docs/just-in-time-mode. They recommend that we should not generate class dynamically as you made.

Just simply understand that tailwind will try to understand your class definition at compile time so that a clear declaration would help tailwind understand what you intend to do at runtime.

Simple example would help you have a better understanding about this:

<div className={`mt-[${size === 'lg' ? '22px' : '17px' }]`}></div>
// Tailwind don't know what kind of class to build
<div className={ size === 'lg' ? 'mt-[22px]' : 'mt-[17px]' }></div>
// Tailwind understand 'mt-[22px]' and 'mt-[17px]' to build
Justin Dang
  • 234
  • 3
  • 7