How to use conditional classes in Tailwind with an extend theme?
12:04 29 Oct 2022

I am making a project in React using Tailwind CSS. I have to use a specific color and add border-{color}, bg-{color}, and more styles depending on a prop. I'm using the approach below but it doesn't work. Can someone help me here?

tailwindconfig.js

//tailwind.config.js
module.exports = {
theme: {
    extend: {
      colors: {
         colorA: '#ff6d00',
         colorB: '#33691e',
         colorC: '#ffd600',
      }
    }
  }
}

My components

function Component() {
  const colors = ['colorA', 'colorB', 'colorC'];
  return (
    <>
      
colorC
{colors.map((color) => ( type={`bg-${color}`}*/ /> ))} ); } function ComponentColor({ type }) { const bgStyle = `bg-${type}`; // const bgStyle = type; return
{type}
; }

I understand that Tailwind is pre-rendered before it is loaded into the browser and only the classes used are bundled into the final style file. I can use a "safelist", but how could I handle the case where I have many colors and CSS properties?

//tailwind.config.js
module.exports = {
theme: {
    extend: {
      colors: {
         colorA: '#ff6d00',
         colorB: '#33691e',
         colorC: '#ffd600',
      }
    }
  },
  safelist: ['bg-colorA', 'bg-colorB', ...],
}

Or there is a way to define the colors outside the Tailwind config and then call inside dynamically to generate the colors and safelist?

reactjs tailwind-css tailwind-css-3