search

Home  >  Q&A  >  body text

Why does concatenated string class name not work in Tailwind?

Every time I end up using the style attribute outside of className because none of the examples below apply styles to my React elements. Can you explain why this is happening and how I can fix it?

I have read the documentation (https://tailwindcss.com/docs/content-configuration#dynamic-class-names) but my usage case is: user selects color from color picker and then I change the background based on the selected color. I can't pass the value of "bg-[colorValue]" to each individual color, so I have to concatenate the value with "bg-[" afterwards. Because I can't map all the colors into the complete class name.

const red500 = "red-500";
const red600Hex = "#dc2626";
const bgColor = "bg-[" + red600Hex + "]";
const bgColor2 = "bg-[" + "#dc2626" + "]";

function App() {
    return (
        <>
            <h1 className={` bg-${red500} `}>Hello</h1>
            <h1 className={` bg-[${red600Hex}] `}>Hello</h1>
            <h1 className={` bg-${`[${red600Hex}]`} `}>Hello</h1>
            <h1 className={` ${bgColor} `}>Hello</h1>
            <h1 className={` ${bgColor2} `}>Hello</h1>
        </>
    );
}


P粉575055974P粉575055974496 days ago708

reply all(1)I'll reply

  • P粉309989673

    P粉3099896732023-07-19 10:57:55

    When template literal strings work properly, you don't need to worry about string concatenation.

    const red500 = 'red-500';
    const red600Hex = '#dc2626';
    const bgColor = `bg-[${red600Hex}]`;
    const bgColor2 = `bg-[${'#dc2626'}]`;
    
    export function App() {
      return (
        <>
          <h1 className={` bg-${red500} `}>Hello</h1>
          <h1 className={` bg-[${red600Hex}] `}>Hello</h1>
          <h1 className={` bg-${`[${red600Hex}]`} `}>Hello</h1>
          <h1 className={` ${bgColor} `}>Hello</h1>
          <h1 className={` ${bgColor2} `}>Hello</h1>
        </>
      );
    }

    Tailwind Playground

    The link above also gave me a warning about concatenation: "Bug Finder: Unexpected string concatenation of literals.eslint"

    I even added an option to dynamically control the color of the last h1, Achieved through status:

    const colors = [
      {value: "#dc2626"},
      {value: "#dc06e6"},
      {value: "#dce606"},
    ]
    
    
    export function App() {
      const [color, setColor] = React.useState(colors[0].value)
      return (
        <>
          <h1 className={`text-green-500 bg-${red500} `}>Hello</h1>
          <h1 className={`bg-[${red600Hex}] `}>Hello</h1>
          <h1 className={`text-green-200 bg-${`[${red600Hex}]`} `}>Hello</h1>
          <h1 className={`${bgColor} `}>Hello</h1>
          <h1 className={`bg-[${color}]`}>Hello</h1>
          <select onChange={(e) => setColor(e.currentTarget.value)}>
            {colors.map(c => <option className={`bg-[${c.value}]`} value={c.value}>{c.value}</option>)}
          </select>
        </>
      );
    }

    reply
    0
  • Cancelreply