React and Tailwind CSS: dynamically generated classes are not being applied

The CSS file generated by Tailwind will only include classes that it recognizes when it scans your code, which means that dynamically generated classes (e.g. col-span-${colSpan}) will not be included.

If you only need to span 2 columns, you could pass boolean values which will trigger the addition of a full col-span-2 or row-span-2 utility class to be added:

const Button = ({ colSpan = false, rowSpan = false, children }) => {
  return (
    <div
      className={`${colSpan ? 'col-span-2' : ''} ${rowSpan ? 'row-span-2' : ''} bg-white p-3 rounded`}
    >
      <div className="flex items-center justify-center">{children}</div>
    </div>
  );
};

Otherwise, you could pass the values as classes to the Button component:

<Button className="col-span-2 row-span-1">=</Button>

const Button = ({ className, children }) => {
  return (
    <div
      className={`${className} bg-white p-3 rounded`}
    >
      <div className="flex items-center justify-center">{children}</div>
    </div>
  );
};

More information: https://tailwindcss.com/docs/content-configuration#dynamic-class-names

Leave a Comment