How to Forward Events in Svelte: Simple Guide with Examples
createEventDispatcher to dispatch events and then re-dispatching them in the parent or using $$restProps with on:event forwarding. This lets the parent listen to events as if they came directly from the child component.Syntax
To forward events in Svelte, you use the createEventDispatcher function inside the child component to create a dispatcher. Then you dispatch events with dispatch('eventName', detail). The parent component listens to these events using on:eventName.
Alternatively, you can forward all events automatically by spreading $$restProps on an element inside the child component.
import { createEventDispatcher } from 'svelte'; const dispatch = createEventDispatcher(); function handleClick() { dispatch('customEvent', { some: 'data' }); } <!-- In markup --> <button on:click={handleClick}>Click me</button>
Example
This example shows a child button component forwarding a click event to its parent. The child dispatches a click event, and the parent listens and reacts.
<!-- ChildButton.svelte --> <script> import { createEventDispatcher } from 'svelte'; const dispatch = createEventDispatcher(); function handleClick() { dispatch('click'); } </script> <button on:click={handleClick}> Forwarded Button </button> <!-- Parent.svelte --> <script> import ChildButton from './ChildButton.svelte'; function onChildClick() { alert('Child button clicked!'); } </script> <ChildButton on:click={onChildClick} />
Common Pitfalls
One common mistake is dispatching events with names that don't match what the parent listens for. Another is forgetting to use createEventDispatcher in the child, so events never reach the parent.
Also, directly forwarding native DOM events requires manually dispatching them or using $$restProps to spread event handlers.
<!-- Wrong: dispatching event with wrong name --> <script> import { createEventDispatcher } from 'svelte'; const dispatch = createEventDispatcher(); function handleClick() { dispatch('wrongEvent'); // Parent listens for 'click', so this won't work } </script> <button on:click={handleClick}>Click me</button> <!-- Right: dispatch event with correct name --> <script> import { createEventDispatcher } from 'svelte'; const dispatch = createEventDispatcher(); function handleClick() { dispatch('click'); } </script> <button on:click={handleClick}>Click me</button>
Quick Reference
- createEventDispatcher(): Creates a function to send events from child to parent.
- dispatch('eventName', detail): Sends an event with optional data.
- on:eventName: Parent listens to child's event.
- $$restProps: Spread to forward all event handlers automatically.