Component Events

Introduction

Svelte 5 introduces a new, simpler way to handle component events. This guide will walk you through the basics of this new approach, making it easy for beginners to understand and implement.

Basic Callback Props

Let's start with a simple example of how to use callback props in Svelte 5.

<script>
  let { onIncrement } = $props();
  let count = $state(0);

  function increment() {
    count++;
    onIncrement(count);
  }
</script>

<button onclick={increment}>Increment: {count}</button>
  • $props() is a Svelte 5-specific feature that declares props for the component.

  • onIncrement is a prop name we've chosen, but you can use any valid JavaScript identifier.

  • on:click is Svelte-specific syntax for adding event listeners.

Now, let's see how to use this component in a parent component:

<script>
  import Counter from './components/Counter.svelte';

  function handleIncrement(newCount) {
    console.log('New count:', newCount);
  }
</script>

<Counter onIncrement={handleIncrement} />
  • import is standard JavaScript syntax for importing modules.

  • onIncrement={handleIncrement} is passing a function as a prop, which is standard JavaScript/JSX syntax.

Let's see how this would appear in the browser:

[Button] Increment: 0

When you click the button, the count will increase, and you'll see log messages in the console.

Conclusion

This guide covers the bare essentials of handling component events in Svelte 5. The new approach using callback props simplifies event handling and makes your code more intuitive.

Last updated