Home >Web Front-end >JS Tutorial >How to Use Dynamic Class Names with Tailwind CSS?
Dynamic Class Names and Tailwind CSS
Dynamically constructing class names in JavaScript is a common practice, but when it comes to Tailwind CSS, it poses a challenge. Tailwind CSS relies on extracting complete unbroken class names from your source files.
As per Tailwind's documentation, dynamically constructing class names using string interpolation or concatenation will result in Tailwind not finding the classes and therefore not generating the corresponding CSS. For instance:
<div class="text-{{ error ? 'red' : 'green' }}-600"></div>
In this example, the text-red-600 and text-green-600 strings don't exist as complete class names, so Tailwind ignores them.
Solutions:
To address this issue, there are several solutions:
<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
const colors = { // ... secondary: darkTheme ? "bg-[#FFFFFF]" : "bg-[#FFFFFF]", // ... };
<p className={`${colors.secondary} text-text-white`}></p>
<p className="text-text-white">
The above is the detailed content of How to Use Dynamic Class Names with Tailwind CSS?. For more information, please follow other related articles on the PHP Chinese website!