Im just experimenting with Tailwind, i want to make a component that receives a colorname and then displays all the values of that color.
const Square = ({ clr }: { clr: string }) => {
return <div className={twMerge("w-[50px] h-[75px]", clr)}></div>;
};
const ColorLine = ({ color }: { color: string }) => {
return (
<div className="flex">
<Square clr={`bg-${color}-50`} />
<Square clr={`bg-${color}-100`} />
<Square clr={`bg-${color}-200`} />
<Square clr={`bg-${color}-300`} />
<Square clr={`bg-${color}-400`} />
<Square clr={`bg-${color}-500`} />
</div>
);
};
However, my squares wont have a background.
The color im receiving in ColorLine is orchid-white.
If i change the value of clr to clr={"bg-orchid-white-300"}
it will work.
After changing it back it keeps working, but initially it doesnt seem to work and im just very confused right now.
This has to do with how Tailwind determines which classes should be generated, see this section of the docs. In short, if you use variables, the compiler cannot know what the eventual classes will be. It cannot infer that bg-${color}-500
will become bg-red-500
, for example.
EDIT: Two more notes for later visitors, taken form the answers by AKX and Karson Jo:
- In your
tailwind.config.js
, you can add asafelist
property, which can either contain literals ("bg-red-50", "bg-red-100", ...
) or regular expressions ({pattern: /bg-[a-z]+-[0-9]{2,3}/}
). See the docs for more details. - Sometimes, in development, it may look like dynamic classes work if you had previously used the literal. This is because the development server will cache classes it previously encountered. If you restart the development server, the dynamic classes will be gone.
The most important implication of how Tailwind extracts class names is that it will only find classes that exist as complete unbroken strings in your source files.
– the docs.
If you always need some certain dynamic classnames to get built into your file, you can use the safelist
configuration:
safelist: [{pattern: /bg-.+-(50|[1-5]00)/}]
would ensure that those bg
classes get included even if Tailwind can’t detect them.
By default, Tailwind will only include utility classes that are used. If a class cannot be statically analyzed for use, it will not be included in the resulting stylesheet.
As for the fact that you hard-coded a value and then converted it to dynamic and it worked again, it’s because Tailwind has a caching mechanism. It won’t take effect after you restart the development server or build.
If you want certain classes to always be included in the final build, you can use safelist.