I’m having trouble with a Tailwind CSS class not updating in the browser, even though it appears to be updated in the DOM tree. Specifically, I’m trying to update the left
property with a dynamic value in a string literal for a React component.
import React, { useState } from "react";
const MIN_VALUE = 10000;
const MAX_VALUE = 20000;
const InputRange = () => {
const [value, setValue] = useState<number>(14000);
const handleSliderChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setValue(parseInt(e.target.value));
};
return (
<div className="mt-4 flex flex-col items-start w-full">
<h2 className="text-base text-center text-primary-black font-bold">
Update the range value
</h2>
<div className="relative pt-8 flex items-center justify-center w-full">
<label
htmlFor="rangeValue"
className={`absolute top-0 left-[${value}px]`}
>
<span>RM{value}</span>
</label>
<input
type="range"
name="value"
value={value}
onChange={handleSliderChange}
id="rangeValue"
min={MIN_VALUE}
max={MAX_VALUE}
className="w-full"
/>
</div>
</div>
);
};
export default InputRange;
Here is the screenshot of the browser’s DOM(chrome):
2
Answers
Tailwind doesn’t generate every possible class for every value you can put in. Instead, it checks your code for class names, and inserts them into the css file. If you want to change the positioning based on an arbitrary value, learn how css works and use inline styles.
Tailwind docs
The problem is that you are dynamically adding the
tailwindCSS
classes in the label. TailwindCSS doesn’t allow you to generate classes dynamically. So when you use the following to generate the class……TailwindCSS will not pick that up as a valid TailwindCSS class and therefore will not produce the necessary CSS.
Instead, you must include the full name of the class in your source code. You can return the full value by using a function like this
where
value
is the state you are passing here.By doing it this way, the entire string for every class is in your source code, so TailwindCSS will know to generate the applicable CSS.
And use it like
Read more: https://tailwindcss.com/docs/content-configuration#class-detection-in-depth