Search code examples
javascriptreactjsnext.jstailwind-css

Tailwind doesn't render font-size with arbitrary value


I am trying to scale a span element based on a number from a variable:

export default async function Tags() {
  const tags = await getTags();

  return (
    <div>
      <Suspense>
        <div className="flex flex-wrap">
          {tags.results?.map((tag) => (
            <span
              key={tag.id}
              className={`pr-4 text-[${tag.font}px]`}
            >
              {tag.name}
            </span>
          ))}
        </div>
      </Suspense>
    </div>
  );
}

It creates desired output if I inspect the page:

<div class="flex flex-wrap">
  <span class="pr-4 text-[17px]">cars</span>
  <span class="pr-4 text-[18px]">sports</span>
  ...
</div>

But it doens't show on the page. If I replace ${tag.font} with a number it works, but not with the variable. What am I doing wrong?

UPDATE

It seems that only certain numbers work like 20 and 36, but now all of them. Why is that?


Solution

  • The reason it's not working is because of this:

    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.

    If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS.

    Dynamic class names in Tailwind

    The reason 20 and 36 could be working is because you have those somewhere else in your codebase and TailwindCSS is generating those classes.

    When working with Tailwind and you need to style an element based on some dynamic data, you should use the style tag.

    {tags.results?.map((tag) => (
        <span
            key={tag.id}
            className="pr-4"
            style={{fontSize: `${tag.font}px`}}
        >
            {tag.name}
        </span>
    ))}