Why does concatenated string class name not work in Tailwind?
P粉575055974
P粉575055974 2023-07-18 18:47:03
0
1
567

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粉575055974
P粉575055974

reply all(1)
P粉309989673

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 (
    <>
      

Hello

Hello

Hello

Hello

Hello

); }

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 (
    <>
      

Hello

Hello

Hello

Hello

Hello

); }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!