Home > Mobile >  Adding a string to a variable in a Tailwind utility class
Adding a string to a variable in a Tailwind utility class

Time:11-27

I'm trying to add a variable to a className and need to append a percentage for it to work. For example the following works:

className="scale-x-[35%]"

But the following doesn't:

className={`scale-x-[${variableNumber}%]`}

What would be the correct way to append the percentage string to my variable?

Edit: Full code

export default function proposalDetail() {
  const [percentage1, setPercentage1] = useState(10);
  const [percentage2, setPercentage2] = useState(35);
  return (
    <div className="relative p-4 my-4 overflow-hidden border border-gray-200 rounded-lg hover:border-indigo-500">
      <div className={`scale-x-${percentage1}% absolute inset-0 w-full origin-top-left bg-indigo-500 bg-opacity-50`}></div>
      <div className="relative text-black z-100 dark:text-white">
      <div className="font-medium">0% burn, 2.5% revenue</div>
      <div className="text-sm">23 voters</div>
      <div className="text-sm">295.7513474746361 QNTFI ({percentage1}%)</div>
    </div>
  </div>
)

CodePudding user response:

className={`scale-x-${percentage1}% ...`} is an attempt to use a dynamic Tailwind utility class. This will not work because Tailwind creates its compiled CSS file by parsing your code and including only fully-formed (non-dynamic) utility classes. For an explanation, see: https://tailwindcss.com/docs/content-configuration#dynamic-class-names

If the possible percentage1 and percentage2 values range from 0 to 100, it's probably best to divide the value by 100 and use a style attribute instead of Tailwind for the transform CSS. For example:

<div style={{transform: `scaleX(${percentage1/100})`}} className="absolute inset-0 w-full origin-top-left bg-indigo-500 bg-opacity-50"></div>

CodePudding user response:

According to the docs, 10 is not a predefined value for the scale class. To add a one off custom value, you can do the following:

className={`scale-x-[${percentage1}]`}

0 is 0%, while 1 is 100%.

  • Related