classnames icon indicating copy to clipboard operation
classnames copied to clipboard

Question about Dynamic class names with Tailwind CSS

Open shinokada opened this issue 2 years ago • 4 comments

According to the Tailwind CSS doc:

As outlined in [Class detection in-depth](https://tailwindcss.com/docs/content-configuration#class-detection-in-depth), 
Tailwind doesn’t actually run your source code and won’t detect dynamically constructed class names.

Don't construct class names dynamically
<div class="text-{{ error ? 'red' : 'green' }}-600"></div>

Always use complete class names
<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>

Do you recommend using classnames with Tailwind CSS?

let buttonType = 'blue';
classNames({ [`text-${buttonType}-500`]: true });

shinokada avatar May 16 '22 22:05 shinokada

I am using classnames with Tailwind CSS.

Like you mentioned, dynamically creating classes won't work. But there is a workaround I have used:

First I create a map, for instance an Map for justify-content class:

const justifyMap = new Map([
    ["center", "justify-center"],
    ["start", "justify-start"],
    ["end", "justify-end"],
    ["between", "justify-between"],
  ]);

Then I dynamically set the className if justify prop is defined:

  const className = classnames("flex", {
    [`${justifyMap.get(justify!)}`]: justify,
  });

We can further abstract the above to some kind of method to keep it cleaner.

patrykmaron avatar May 17 '22 17:05 patrykmaron

So in your case, you would want to do something like:

const buttonTypeMap = new Map([
    ["blue", "text-blue-400"],
    ["red", "text-red-400"],
    ["yellow", "text-yellow-400"],
  ]);

const className = classnames( {
    [`${buttonTypeMap.get(buttonType!)}`]:  buttonType,
  });

patrykmaron avatar May 17 '22 17:05 patrykmaron

@patrykmaron Thank you for your reply. What is ! at the end of justify! and buttonType!?

shinokada avatar May 18 '22 01:05 shinokada

@shinokada

What is ! at the end of justify! and buttonType!?

That is TypeScript's non-null assertion operator.

scott-lc avatar May 20 '22 14:05 scott-lc

I was stuck with the same kinf of problem ! you helped a lot, thanks =)

sylvain-guehria avatar Nov 18 '22 20:11 sylvain-guehria