Dynamic Class Binding in Svelte
Introduction to Dynamic Class Binding
In the previous lesson, you learned about scoped, component, and global styles in Svelte, which are essential for creating clean and maintainable user interfaces. Now, we’ll take styling a step further by introducing dynamic class binding. This technique allows you to apply or remove CSS classes based on the state of your application, making your components more interactive and visually dynamic.
Dynamic class binding is particularly useful when you want to change the appearance of an element in response to user actions, such as clicking a button or hovering over an element. In Svelte 5, this is achieved using the $state rune for reactivity and event handlers like onclick, onmouseenter, and onmouseleave. By the end of this lesson, you’ll understand how to use these tools to create components that respond to user interactions with smooth and engaging visual changes.
Basic Class Binding with `$state`
Let’s start by exploring how to bind a class to a state variable in Svelte. In Svelte 5, reactivity is handled using the $state rune, which replaces older patterns like stores and $:. Here’s a simple example where we toggle a class (active) on a button when it’s clicked:
In this example:
- We define a state variable
activeusing$state(false), which initializes tofalse. - The
classattribute of the button uses an array to combine the static classbtnwith the conditional classactive. Whenactiveistrue, theactiveclass is applied. - The
onclickevent handler toggles the value ofactivebetweentrueandfalse.
When you click the button, it will toggle between the default and active styles, changing the background color to blue and the text color to white.
Handling Multiple Classes and Conditions
Sometimes, you’ll want to apply multiple classes conditionally based on different states. For example, you might want to highlight a button when the user hovers over it while also toggling an active state. Here’s how you can achieve this:
In this example:
- We introduce a second state variable
highlightedto track whether the button is being hovered over. - The
classattribute now includes bothactiveandhighlightedclasses, which are applied conditionally based on their respective state variables. - The
onmouseenterandonmouseleaveevent handlers update thehighlightedstate when the user hovers over or leaves the button.
When you hover over the button, it will gain a subtle box shadow, and clicking it will toggle the active state, changing its background color.
