skip to Main Content

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.

3

Answers


  1. 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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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.

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