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.

CSS Transitions for Dynamic Classes

To make your dynamic class changes smoother, you can use CSS transitions. Transitions allow you to animate changes in CSS properties, such as background-color or box-shadow, creating a more polished user experience. Here’s how to add transitions to the previous example:

<style>
  .btn {
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    background-color: #ddd;
    cursor: pointer;
    transition: background-color 0.3s ease, box-shadow 0.3s ease;
  }

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

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

In this updated CSS:

  • The transition property is added to the .btn class, specifying that changes to background-color and box-shadow should animate over 0.3 seconds with an easing effect.
  • When the active or highlighted classes are applied or removed, the changes will now animate smoothly instead of happening instantly.
Real-World Example Breakdown

Let’s break down the provided solution.svelte code to see how all these concepts come together:

<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;
    transition: background-color 0.3s ease;
  }

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

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

In this example:

  • The active and highlighted states are managed using $state.
  • The class attribute combines the static btn class with the conditional active and highlighted classes.
  • Event handlers (onclick, onmouseenter, onmouseleave) update the state variables based on user interactions.
  • CSS transitions ensure that changes to background-color and box-shadow are smooth and visually appealing.
When Object Syntax Isn't Enough: Using JavaScript Expressions for Class Binding

In most cases, the object shorthand syntax works well for dynamic class binding. However, there are situations where the state variable name does not match the class name, making the shorthand approach less effective.

Example: Active and Disabled States
Summary and Practice Preparation

In this lesson, you learned how to use dynamic class binding in Svelte to create interactive and visually dynamic components. Here’s a quick recap of the key concepts:

  • Dynamic Class Binding: Use $state to manage state variables and conditionally apply classes based on their values.
  • Multiple Classes: Combine multiple classes conditionally using the object syntax in the class attribute.
  • CSS Transitions: Add smooth animations to class changes using the transition property in CSS.
  • Event Handling: Use event handlers like onclick, onmouseenter, and onmouseleave to update state variables in response to user interactions.

In the practice exercises, you’ll apply these concepts to create components that respond to user actions with dynamic styling. Remember, Svelte 5 is pre-installed on CodeSignal, so you can focus on coding without worrying about setup. Experiment with the examples and explore how dynamic class binding can enhance your user interfaces. Great job completing this lesson—you’re one step closer to mastering styling and transitions in Svelte!

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