reactjstailwind-csscreate-react-app

Dynamic style rendering tailwindcss


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>
    );

Solution

  • 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:

    <span className={`${true ? 'text-red-400' : 'text-blue-400'}`}>test</span>
    

    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.