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`
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.
