I want to render an element with a random color at runtime at every documentstart, using ReactJS and TailwindCSS. However, even though looking at the element through the inspector and seeeing the class properly, it still doesn’t work. Here is the code:
const colors = ["red", "orange", "amber", "yellow", "lime", "green", "emerald", "teal", "cyan", "light-blue", "blue", "indigo", "violet", "purple", "fuchsia", "pink", "rose"];
const [theme, setTheme] = useState("orange");
useEffect(() => {
setTheme(colors[Math.floor(Math.random() * colors.length)]);
}, []);
return (
<span className={`text-${theme}-400`}>test</span>
);
2
Answers
in Tailwind you can’t use dynamic class naming like bg-${color}.
This because when Tailwind compiles its CSS, it looks up over all of your code and checks if a class name matches.
If you want dynamic name classes you should write all the class name.
It expect you to write something like this:
I know this make the code longer and more verbose but this is the only way in vanilla tailwindcss, you can use some external packages like clsx or xwind.
Is it advised to utilise a dynamic class in a tailwind?
Ans: No
According to Docs
Is there work around ?
Ans: Yes, use Safelisting classes in your tailwind.config.cs
Particular to you, you want to have text with different colors. You can use regular expressions to include all the colors you want using pattern and specify the shades accordingly .
Note: You can force Tailwind to create variants as well:
In
tailwind.config.js
To include all the bg-colors, you can use the following code: