{Svelte} How to Dynamically Inject CSS Classes
Hi, today I want to show you how I dynamically assign CSS classes to an HTML tag. I really like Svelte, but I miss the class bindings in VueJS https://vuejs.org/guide/essentials/class-and-style.html#binding-html-classes and since the Svelte team has no current plans to add this feature, I've been using the following solution:
We create the useClasses.js
file, I like to place it in my Helpers folder, but obviously you can save it anywhere you would like to.
export default function useClasses(obj) {
let classes = [];
Object.keys(obj).forEach((key) => {
if (obj[key]) classes.push(key);
});
return classes.join(" ");
}
We can use this function like this:
<div class="{useClasses({
'bg-white text-black': conditionA && !darkMode,
'bg-black text-white': conditionB && darkMode
})}"></div>
That's all there is to it.
If you have any questions, please leave a comment below.