Give variable style properties react

Viewed 32

I am trying to build a custom progress bar using React. I have a calculated percentage, I want to set as a width of some div element. Currently I tried it using Tailwind CSS:

<div className={"p-1 w-[" + percentage + "%]"}></div>

But it does not work. So how can I apply this kind of variable styling in React?

2 Answers

Assuming you have the needed Tailwind classes, create a variable to store the classes for the progress bar:

const progressBarClasses = `p-1 w-${progress}`

Assign the classes to the div like this:

<div className={progressBarClasses}></div>

You cannot put expressions in plain JSX, you must use the special curly braces syntax to evaluate an expression and it will resolve to a value:

<div className={"p-1 w-[" + percentage + "%]"}></div>
Related