classnames
classnames copied to clipboard
Question about Dynamic class names with Tailwind CSS
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 });
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.
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 Thank you for your reply. What is !
at the end of justify!
and buttonType!
?
@shinokada
What is ! at the end of justify! and buttonType!?
That is TypeScript's non-null assertion operator.
I was stuck with the same kinf of problem ! you helped a lot, thanks =)