Welcome to the amazing world of Svelte, where building highly interactive web applications is a breeze . In this tutorial, we will learn how to use conditional classes in Svelte.
What are conditional classes?
If you've been building web applications with one of the UI frameworks out there, you probably came across a situation where you need an element to have some style based on some conditions. For example, you might want to change the background color of a button when it's clicked . This is where conditional classes come in handy.
If you want to read more about how Svelte handles CSS in general, check out this article.
They can be incredibly helpful when you want to change the appearance of your web app based on user interactions, data changes, or other events.
This code is pretty straightforward. We are selecting the button and the body element, then we are adding an event listener to the button that toggles the
dark class on the body element.
But now imagine you are building a large application with a lot of elements that need to have conditional classes; responding to various interactions, events, and data changes. This can get messy pretty quickly, and you will wish to have a more declarative way to do this.
Conditional classes in Svelte
Let's see a naive example of how we can use conditional classes in Svelte:
In this code, the reactive variable
isDark 's value is set to
false by default. It is changed to its opposite whenever the button is clicked. Then, we are conditionally adding the
dark class to the body element based on the value of
Using the class directive
While the above code works well, it can be improved by using the Svelte
class directive. The
class directive allows you to bind some class names to an element class attribute. Let's see how we can use it for the example above:
Practical example: setting active class on a navigation menu in SvelteKit
Let's say you have a navigation menu with a list of links. You want to set the active class on the link that is currently active. Here is how you would do that with SvelteKit:
$app/stores module comes from SvelteKit and contains information about the current page. We are using the
$page.url.pathname to check if the current link is active or not.
Conditional classes are a great way to add some style to your web app based on some conditions. They are especially useful when you are building large applications with a lot of elements that need to have conditional classes.
You can either use ternary or conditional expressions in an element class attribute or use the
class directive to bind some classes to an element class attribute.