61

I am currently building a component library for my next project with TailwindCss, I just ran into a small issue when working on the Button component.

I'm passing in a prop like 'primary' or 'secondary' that matches a color I've specified in the tailwind.config.js then I want to assign that to the button component using Template literals like so: bg-${color}-500

<button
    className={`
    w-40 rounded-lg p-3 m-2 font-bold transition-all duration-100 border-2 active:scale-[0.98]
    bg-${color}-500 `}
    onClick={onClick}
    type="button"
    tabIndex={0}
  >
    {children}
</button>

The class name comes through in the browser just fine, it shows bg-primary-500 in the DOM, but not in the applied styles tab.

enter image description here

The theming is configured like so:

  theme: {
    extend: {
      colors: {
        primary: {
          500: '#B76B3F',
        },
        secondary: {
          500: '#344055',
        },
      },
    },
  },

But it doesn't apply any styling. if I just add bg-primary-500 manually it works fine.

I'm honestly just wondering if this is because of the JIT compiler not picking dynamic classnames up or if I'm doing something wrong (or this is just NOT the way to work with tailWind).

Any help is welcome, thanks in advance!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Wesley Janse
  • 1,244
  • 1
  • 7
  • 14

12 Answers12

35

So after finding out that this way of working is not recommended and that JIT doesn't support it (Thanks to the generous commenters). I have changed the approach to a more 'config' based approach.

Basically I define a const with the basic configuration for the different props and apply those to the component. It's a bit more maintenance work but it does the job.

Here is the example of a config. (Currently without typing) and up for some better refactoring but you'll get the idea.

const buttonConfig = {
  // Colors
  primary: {
    bgColor: 'bg-primary-500',
    color: 'text-white',
    outline:
      'border-primary-500 text-primary-500 bg-opacity-0 hover:bg-opacity-10',
  },
  secondary: {
    bgColor: 'bg-secondary-500',
    color: 'text-white',
    outline:
      'border-secondary-500 text-secondary-500 bg-opacity-0 hover:bg-opacity-10',
  },

  // Sizes
  small: 'px-3 py-2',
  medium: 'px-4 py-2',
  large: 'px-5 py-2',
};

Then I just apply the styling like so:

  <motion.button
    whileTap={{ scale: 0.98 }}
    className={`
    rounded-lg font-bold transition-all duration-100 border-2 focus:outline-none
    ${buttonConfig[size]}
    ${outlined && buttonConfig[color].outline}
    ${buttonConfig[color].bgColor} ${buttonConfig[color].color}`}
    onClick={onClick}
    type="button"
    tabIndex={0}
  >
    {children}
  </motion.button>
Wesley Janse
  • 1,244
  • 1
  • 7
  • 14
  • 8
    It's even possible to just add the tailwind classes (you want to have included for dynamic usage) as comments somewhere in your code. Allows using `bg-${color}-100 text-${color}-500` as long as u mention `bg-accent-100 text-accent-500` in a comment somewhere for every color that you want to include. – Patrick Hellebrand Jan 16 '22 at 00:56
  • @morganney This was for a small personal project, I like to educate myself on all the front-end frameworks in how they work and what the caveats are. I still think you can build really flexible and scalable front-ends with TailWind, it's just how you set it up and decide to use it. And as statet below, this isn't really an issue anymore since the latest updates. – Wesley Janse Feb 21 '22 at 09:02
  • @morganney This is hardly a significant problem – forresthopkinsa Sep 10 '22 at 22:29
  • @forresthopkinsa It is a significant problem if you try to generate lots of dynamic class strings. Your bundle size will be massive, because you will end up safelisting a large proportion of all tailwindcss classes. – lmonninger Nov 08 '22 at 23:23
  • @WesleyJanse I was just doing some more asking around and experimenting with this. It appears, if you are in an SSR context, you can run postcss with the tailwind plugin on rendered HTML. And, the performance hit doesn't appeared to be significant (< 100ms). This allows you to use dynamic classnames, so long as (1) you're using a proper SSR framework like Nuxt and (1.1) Javascript which changes the classnames at browser runtime aren't included in the bundle. – lmonninger Nov 10 '22 at 18:25
22

this way of writing Tailwind CSS classes is not recommended. Even JIT mode doesn't support it, to quote Tailwind CSS docs: "Tailwind doesn’t include any sort of client-side runtime, so class names need to be statically extractable at build-time, and can’t depend on any sort of arbitrary dynamic values that change on the client"

tnemele12
  • 903
  • 7
  • 16
10

EDIT: Better implementation 2022 - https://stackoverflow.com/a/73057959/11614995

Tailwind CSS does not support dynamic class names (see here). However, there's still a way to accomplish this. I needed to use dynamically build class names in my Vue3 application. See the code example below.

Upon build tailwind scanes your application for classes that are in use and automatically purges all other classes (see here). There is however a savelist feature that you can use to exclude classes from purging - aka they will always make it to production.

I have created a sample code below, that I use in my production. It combines each color and each color shade (colorValues array).

This array of class names is passed into the safelist. Please note, that by implementing this feature you ship more css data to production as well as ship css classes you may never use.

const colors = require('./node_modules/tailwindcss/colors');
const colorSaveList = [];
const extendedColors = {};
const colorValues = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900];

for (const key in colors) {
  

  // To avoid tailWind "Color deprecated" warning
  if (!['lightBlue', 'warmGray', 'trueGray', 'coolGray',  'blueGray'].includes(key))
  {
    extendedColors[key] = colors[key];
    for(const colorValue in colorValues) {
       colorSaveList.push(`text-${key}-${colorValue}`);
       colorSaveList.push(`bg-${key}-${colorValue}`);
    }
  }
}


module.exports = {
  content: [
    "./index.html",
    "./src/**/*.{vue,js,ts,jsx,tsx}"
  ],
  safelist: colorSaveList,
  theme: {
   extend: {
      colors: extendedColors
   }
  },
  plugins: [
    require('tailwind-scrollbar'),
  ]

}
A. Mrózek
  • 101
  • 2
  • 7
  • 1
    I wonder if `safelist` is a better alternative then auto-generating all the possible combinations in a helper function and then simply call that function to dynamically look up the classnames. I wrote this gist regarding the topic: https://gist.github.com/tahesse/345830247456980d1c8ac6e53a2dd879 – tafaust Jul 17 '22 at 08:27
  • 1
    @tahesse I like your solution. It could be used as an external script or "plugin" for other devs. My code is more like a hotfix or a quickfix. As you mention in the gist you have to call into account the classes you might not use. But still, you can modify my solution to only use classes that you want and safeList them. I find my solution quite easy as you take advantage of a feature already included in TailWindCSS. So to answer your question. I think it's "cleaner" to use my solution insted of writing CSS classes directly to the file via node fs. But still, it's just my opinion. – A. Mrózek Jul 18 '22 at 15:15
  • this is no longer working in 2022 I believe. Added an updated version in a post below – mbdavis Jul 20 '22 at 20:45
  • It's still working in 2022. We use it in our production codebase. I have added a link to your implementation to my original anwer as I find it better. Thanks for tweaking my code. :) – A. Mrózek Jul 21 '22 at 09:33
6

If someone comes across in 2022 - I took A. Mrózek's answer and made a couple of tweaks to avoid deprecated warnings and an issue with iterating non-object pallettes.

const tailwindColors = require("./node_modules/tailwindcss/colors")
const colorSafeList = []

// Skip these to avoid a load of deprecated warnings when tailwind starts up
const deprecated = ["lightBlue", "warmGray", "trueGray", "coolGray", "blueGray"]

for (const colorName in tailwindColors) {
  if (deprecated.includes(colorName)) {
    continue
  }

  const shades = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900]

  const pallette = tailwindColors[colorName]

  if (typeof pallette === "object") {
    shades.forEach((shade) => {
      if (shade in pallette) {
        colorSafeList.push(`text-${colorName}-${shade}`)
        colorSafeList.push(`bg-${colorName}-${shade}`)
      }
    })
  }
}

// tailwind.config.js
module.exports = {
  safelist: colorSafeList,
  content: ["{pages,app}/**/*.{js,ts,jsx,tsx}"],
  theme: {
    extend: {
      colors: tailwindColors,
    },
  },
  plugins: [],
}
mbdavis
  • 3,861
  • 2
  • 22
  • 42
  • 1
    Correct me if I'm wrong. But shouldn't you use **continue** instead of **break** in the for loop when checking, if the colorName is included in the deprecated array? Otherwise upon finding the deprecated color you break the cycle and no more colors are added to the tailwindColors array. – A. Mrózek Jul 21 '22 at 09:49
6

this might be a bit late, but for the people bumping this thread.

the simplest explaination for this is;

Dynamic Class Name does not work unless you configured Safelisting for the Dynamic class name,

BUT, Dynamic Class works fine so long as its a full tailwind class name.

its stated here

this will not work

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

but this one works

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

its states;

As long as you always use complete class names in your code, Tailwind will generate all of your CSS perfectly every time.

the longer explanation;

Tailwind will scan all the files specified in module.exports.content inside tailwind.config.js and look for tailwind classes, it does not even have to be in a class attribute and can even be added in commented lines, so long as the full class name is present in that file and class name is not dynamically constructed; Tailwind will pull the styling for that class,

so in your case, all you have to do is put in the full class name inside that file for all the possible values of your dynamic class something like this

<button className={ color === 'primary' ? 'bg-primary-500' : 'bg-secondary-500'}>
    {children}
</button>

or the method I would prefer

<!-- bg-primary-500 bg-secondary-500 -->
<button className={`bg-${color}-500 `}>
    {children}
</button>

here's another example, although its Vue, the idea would be the same for any JS framework

<template>
    <div :class="`bg-${color}-100 border-${color}-500 text-${color}-700 border-l-4 p-4`" role="alert">
        test
    </div>
</template>
<script>
    /* all supported classes for color props 
    bg-red-100 border-red-500 text-red-700
    bg-orange-100 border-orange-500 text-orange-700
    bg-green-100 border-green-500 text-green-700
    bg-blue-100 border-blue-500 text-blue-700
    */
    export default {
        name: 'Alert',
        props: {
            color: {type: String, default: 'red'}
        }
    }
</script>

and the result would be this

<Alert color="red"></Alert> <!-- this will have color related styling-->
<Alert color="orange"></Alert> <!-- this will have color related styling-->
<Alert color="green"></Alert> <!-- this will have color related styling-->
<Alert color="blue"></Alert> <!-- this will have color related styling-->
<Alert color="purple"></Alert> <!-- this will NOT have color related styling as the generated classes are not pre-specified inside the file -->
silver
  • 4,433
  • 1
  • 18
  • 30
5

For tailwind JIT mode or v3 that uses JIT, you have to ensure that the file where you export the object styles is included in the content option in tailwind.config.js, e.g.

 content: ["./src/styles/**/*.{html,js}"], 
Blessing
  • 2,450
  • 15
  • 22
  • I had the same problem and this is actually what I was missing out : I had my utility classes imported from a local data object stored in a custom folder, so that Tailwind couldn't reference them. I just had to complete the "content" array with my file. – Stéphane Changarnier Dec 15 '21 at 09:42
  • Thanks for letting me know, haven't looked into Tailwind V3. So I don't know what's the better approach right now – Wesley Janse Dec 23 '21 at 20:09
  • It's not about tailwind v3 only, it's just the JIT mode. – Blessing Dec 25 '21 at 00:01
2

Now could use safeListing

and tailwind-safelist-generator package to "pregenerate" our dynamics styles.

With tailwind-safelist-generator, you can generate a safelist.txt file for your theme based on a set of patterns.

Tailwind's JIT mode scans your codebase for class names, and generates CSS based on what it finds. If a class name is not listed explicitly, like text-${error ? 'red' : 'green'}-500, Tailwind won't discover it. To ensure these utilities are generated, you can maintain a file that lists them explicitly, like a safelist.txt file in the root of your project.

Daher
  • 1,001
  • 10
  • 10
2

Is it recommended to use dynamic class in tailwind ?

No

Using dynamic classes in tailwind-css is usually not recommended because tailwind uses tree-shaking i.e any class that wasn't declared in your source files, won't be generated in the output file. Hence it is always recommended to use full class names

According to Tailwind-css docs

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

Isn't there work around ?

Yes

As a last resort, Tailwind offers Safelisting classes.

Safelisting is a last-resort, and should only be used in situations where it’s impossible to scan certain content for class names. These situations are rare, and you should almost never need this feature.

In your example,you want to have 100 500 700 shades of colors. You can use regular expressions to include all the colors you want using pattern and specify the shades accordingly .

Note: You can force Tailwind to create variants as well:

In tailwind.config.js

module.exports = {
  content: [
    './pages/**/*.{html,js}',
    './components/**/*.{html,js}',
  ],
  safelist: [
    {
      pattern: /bg-(red|green|blue|orange)-(100|500|700)/, // You can display all the colors that you need
      variants: ['lg', 'hover', 'focus', 'lg:hover'],      // Optional
    },
  ],
  // ...
}
EXTRA: How to automate to have all tailwind colors in the safelist
const tailwindColors = require("./node_modules/tailwindcss/colors")
const colorSafeList = []

// Skip these to avoid a load of deprecated warnings when tailwind starts up
const deprecated = ["lightBlue", "warmGray", "trueGray", "coolGray", "blueGray"]

for (const colorName in tailwindColors) {
  if (deprecated.includes(colorName)) {
    continue
  }

  // Define all of your desired shades
  const shades = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900]

  const pallette = tailwindColors[colorName]

  if (typeof pallette === "object") {
    shades.forEach((shade) => {
      if (shade in pallette) {
       // colorSafeList.push(`text-${colorName}-${shade}`)  <-- You can add different colored text as well 
        colorSafeList.push(`bg-${colorName}-${shade}`)
      }
    })
  }
}

// tailwind.config.js
module.exports = {
  safelist: colorSafeList,                      // <-- add the safelist here
  content: ["{pages,app}/**/*.{js,ts,jsx,tsx}"],
  theme: {
    extend: {
      colors: tailwindColors,
    },
  },
  plugins: [],
}

Note: I have tried to summarize the answer in all possible ways, In the combination of all possible answers.Hope it helps

krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
1

In v3 as Blessing said you can change the content array to support that.

I had this

const PokemonTypeMap = {
  ghost: {
    classes: "bg-purple-900 text-white",
    text: "fantasma",
  },
  normal: {
    classes: "bg-gray-500 text-white",
    text: "normal",
  },
  dark: {
    classes: "bg-black text-white",
    text: "siniestro",
  },
  psychic: {
    classes: "bg-[#fc46aa] text-white",
    text: "psíquico",
  },
};

function PokemonType(props) {
  const pokemonType = PokemonTypeMap[props.type];

  return (
    <span
      className={pokemonType.classes + " p-1 px-3 rounded-3xl leading-6 lowercase text-sm font-['Open_Sans'] italic"}
    >
      {pokemonType.text}
    </span>
  );
}

export default PokemonType;

something similar to your approach, then I moved the array to a JSON file, it thought was working fine, but was browser caché... so following Blessing's response, you can add .json like this

content: ["./src/**/*.{js,jsx,ts,tsx,json}"],

Finally I have this code, it's better in my view.

import PokemonTypeMap from "./pokemonTypeMap.json";

function PokemonType(props) {
  const pokemonType = PokemonTypeMap[props.type];
    
  return (
    <span className={pokemonType.classes + " p-1 px-3 rounded-3xl leading-6 lowercase text-sm font-['Open_Sans']"}>
      {pokemonType.text}
    </span>
  );
}
    
export default PokemonType;
Dharman
  • 30,962
  • 25
  • 85
  • 135
1

In Nextjs 13.4+ with tailwind you can use combination of both clsx & twMerge

clsx: For Object based className

const [pending, setPending] = useState(false);
<button className={ 
    "px-4", 
    {
       "bg-blue-500":pending, // if pending is true apply blue background
    }
  }
/>

twMerge: For effectively merging tailwind classes,

<button className={twMerge(
    "bg-blue-500 px-4",
    "bg-black"
   )}
/>

Utility Function /lib/utils.ts

import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"
 
export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

Use it as page.tsx


import { cn } from "@/lib/utils";
export default function Component(){
   return <div className={cn(
              "bg-black font-sans",
              "bg-white h-full", 
               {
                 "px-5":pending, // if pending is true apply padding
               }
           )}
         />
}

For further refer: cn() - Every Tailwind Coder Needs It (clsx + twMerge)

krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
0

I had a similar issue, instead of passing all the possible configs, I just pass the data to the style property of the HTML. This is far more efficient!

or

Pass a class name as a prop and let the user of the package write the styles to that class.

const CustomComp = ({
  keyColGap = 0,
  keyRowGap = 0,
  className = '',
}: Props) => {
  const classNameToRender = (): string => {
    return `m-1 flex flex-col ${className}`.trim();
  };

  const rowStylesToRender = (): React.CSSProperties | undefined => {
    const styles: React.CSSProperties | undefined = { gap: `${keyRowGap}rem` };

    return styles;
  };

  const colStylesToRender = (): React.CSSProperties | undefined => {
    const styles: React.CSSProperties | undefined = { gap: `${keyColGap}rem` };

    return styles;
  };

return (
  <div className={classNameToRender()} style={rowStylesToRender()}>
    {layout.map((row) => {
    return (
      <div
        className={`flex justify-around`}
        style={colStylesToRender()}
        key={row}
      >
        /* Some Code */
      </div>
    );
  })}
  </div>
}
YHR
  • 181
  • 1
  • 8
0

2023 Update

The TailwindUI library (created by Tailwind) uses a handy little helper function which you can define in your app (no dependencies required):

export function classNames(...classes) {
  return classes.filter(Boolean).join(' ')
}

Then in any file you can simply add together strings of classes:

className={
  classNames(
    // This could be a string representing classes passed into the component
    "flex flex-col",
    primary ? "bg-teal-600" : "bg-white",
    active ? 'bg-slate-100' : '',
  )
}
Kitson
  • 1,153
  • 9
  • 22