reactjstailwind-css

How can I force Tailwind to include a color?


In one of my React components, I receive a color palette name, and want to use it to change the colors in my component.

My attempt:

    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 (e.g. text-primary-600) isn't present anywhere in the app, it doesn't get bundled with the styles and my link isn't colored.

How can I force my additional styles to be bundled?


Solution

  • 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