Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62
Subscribe to my email list now at http://jauyeung.net/subscribe/
Svelte is an up and coming front end framework for developing front end web apps.
It’s simple to use and lets us create results fast.
In this article, we’ll look at how to change class names dynamically with the Svelte class
directive.
Class Directive
We can use the class
directive with an expression to return the class to display based on the condition.
Also, we can add class names as modifiers and the condition to display it as the value as pass in.
For instance, we can write the following code to toggle a class:
App.svelte
:
<script>
let enableFoo;
</script>
<style>
.foo {
color: red;
}
</style>
<button
on:click="{() => enableFoo = !enableFoo}"
>
Toggle Class
</button>
<p class="{enableFoo ? 'foo': ''}">foo</p>
In the code above, we have class=”{enableFoo ? ‘foo’: ‘’}”
to toggle the foo
class on when the enableFoo
variable is true
since we return 'foo'
then. Otherwise, we have no class apply to the p element.
The class
directive conditionally applies the foo
class to the p element since we added the class
directive to that element.
The button toggles the enableFoo
on and off, which is used to return 'foo'
when enableFoo
is true
. Otherwise, we return an empty string, which means no class.
The foo
class sets the color to red. So the text in the p tag will be toggle between red and black.
We can also write the code to do the same thing as follows:
App.svelte
:
<script>
let enableFoo;
</script>
<style>
.foo {
color: red;
}
</style>
<button
on:click="{() => enableFoo = !enableFoo}"
>
Toggle Class
</button>
<p class:foo="{enableFoo}">foo</p>
We changed:
class="{enableFoo ? 'foo': ''}"
to:
class:foo="{enableFoo}
foo
is the class name, which the modifier for the class
directive.
If our class is the same as our variable name for toggling on a class on and off, then we can shrink the class directive code with the shorthand.
For instance, instead of writing:
<script>
let foo;
</script>
<style>
.foo {
color: red;
}
</style>
<button
on:click="{() => foo = !foo}"
>
Toggle Class
</button>
<p class:foo="{foo}">foo</p>
We can write:
<script>
let foo;
</script>
<style>
.foo {
color: red;
}
</style>
<button
on:click="{() => foo = !foo}"
>
Toggle Class
</button>
<p class:foo>foo</p>
They both toggle the foo
class. class:foo=”{foo}”
is the same as class:foo
.
Conclusion
The class
directive lets us conditionally apply a class to an element. We can do that either by passing in an expression to conditionally return a class name to apply.
Or we can add the class name as the modifier to the class
directive and then pass in the condition to add the class as the value we pass into the directive.