How to force tailwind to include a color?

Viewed 29

In one of my react component, I receive a color palette, and want to use a variation. Basically, here is what I done to have a color variation:

import { Link } from 'react-router-dom';

export interface LinkModel {
  to: string;
  label: string;
  color?: string;
}

export const Alink = ({ to, label, color = 'primary' }: LinkModel) => {
  return (
    <div>
      <Link to={to} className={'font-medium text-' + color + '-600 hover:text-' + color + '-500'}>
        {label}
      </Link>
    </div>
  );
};

I noticed that IF a combination(like text-primary-600) isn't present anywhere in the app, it just doesnt get bundled the styles and my link isn't colored.

How to force some styles to be bundled?

1 Answers

Yes, you are correct that Tailwind does not detect dynamic class names.

One option is to add safelist classes to your Tailwind config. https://tailwindcss.com/docs/content-configuration#safelisting-classes

Another option is to include the full class string in your code.

Here is one possible way to do it by adding an object with all the combinations.

const variantsLookup = {
  primary: 'font-medium text-slate-600 hover:text-slate-500',
  blue: 'font-medium text-blue-600 hover:text-blue-500',
  red: 'font-medium text-red-600 hover:text-red-500',
}

And then the class can be added based on the color prop.

<Link to={to} className={`${variantsLookup[color]}`}>
  {label}
</Link>

Full credit to Simon for this idea. https://www.protailwind.com/just-in-time-friendly-style-variants-in-tailwind-css-ui-components-part-1

Related