Home >Web Front-end >CSS Tutorial >How to Dynamically Manage Tailwind CSS Classes with Template Literals?
Dynamic Class Changes in TailwindCSS with Template Literals
In TailwindCSS, template literals provide a convenient way to dynamically change classes based on state or props. However, syntax errors can occur if used incorrectly.
One common issue is attempting to dynamically add or remove a class with a style rule, such as:
const [click, setClick] = useState(false); const closeNav = () => { setClick(!click); }; const openNav = () => { setClick(!click); }; <div className=" absolute inset-0 ${click ? translate-x-0 : -translate-x-full } transform z-400 h-screen w-1/4 bg-blue-300 " > <XIcon onClick={closeNav} className=" absolute h-8 w-8 right-0 " /> </div>;
To resolve this, enclose the class name within backticks (`):
<div className={`absolute inset-0 ${click ? 'translate-x-0' : '-translate-x-full'} transform z-400 h-screen w-1/4 bg-blue-300`}> </div>
Alternatively, you can use the following syntax:
<div className={'absolute inset-0 ' + (click ? 'translate-x-0' : '-translate-x-full') + ' transform z-400 h-screen w-1/4 bg-blue-300'}> </div>
Avoid using string concatenation, as TailwindCSS may remove unused classes in the production build:
<div className={`text-${error ? 'red' : 'green'}-600`}> </div>
Instead, select the complete class name:
<div className={`${error ? 'text-red-600' : 'text-green-600'}`}> </div>
or:
<div className={error ? 'text-red-600' : 'text-green-600'}> </div>
Additional options include classnames and twin.macro.
Here are some helpful resources:
The above is the detailed content of How to Dynamically Manage Tailwind CSS Classes with Template Literals?. For more information, please follow other related articles on the PHP Chinese website!