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:

<script>
  let active = $state(false);
  let highlighted = $state(false);
</script>

<button
  class={["btn", { active, highlighted }]}
  onclick={() => active = !active}
  onmouseenter={() => highlighted = true}
  onmouseleave={() => highlighted = false}
>
  Toggle Active State
</button>

<style>
  .btn {
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    background-color: #ddd;
    cursor: pointer;
  }

  .btn.active {
    background-color: #007bff;
    color: white;
  }

  .btn.highlighted {
    box-shadow: 0 0 8px rgba(0, 123, 255, 0.5);
  }
</style>

In this example:

  • We introduce a second state variable highlighted to track whether the button is being hovered over.
  • The class attribute now includes both active and highlighted classes, which are applied conditionally based on their respective state variables.
  • The onmouseenter and onmouseleave event handlers update the highlighted state 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.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal