Dynamically build classnames in TailwindCss

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>

Leave a Comment