Event forwarding lets a component pass events it receives up to its parent. This helps keep components simple and reusable.
Event forwarding in Svelte
<ChildComponent on:eventName /> <!-- Inside ChildComponent.svelte --> <button>Click me</button> <!-- Inside WrapperComponent.svelte --> <ChildComponent on:click />
Use on:eventName on the child component tag to forward events.
The child component must emit the event normally for forwarding to work.
click event from the Button component to the parent.<Button on:click />
input event from a custom input component.<CustomInput on:input />
customEvent from the child.<ChildComponent on:customEvent />
The Button component dispatches a click event when clicked. The Wrapper component listens for this event using on:click and shows an alert. This is event forwarding in action.
<!-- Button.svelte --> <script> import { createEventDispatcher } from 'svelte'; const dispatch = createEventDispatcher(); function handleClick() { dispatch('click'); } </script> <button on:click={handleClick} aria-label="Click me button">Click me</button> <!-- Wrapper.svelte --> <script> import Button from './Button.svelte'; function handleClick() { alert('Button clicked! Event forwarded to Wrapper'); } </script> <Button on:click={handleClick} />
Event forwarding only works if the child component dispatches the event using createEventDispatcher or native DOM events.
You can forward multiple events by adding multiple on:event handlers on the child component.
Use aria-label or other accessibility attributes on interactive elements to help screen readers.
Event forwarding passes events from child to parent components easily.
Use on:eventName on the child component tag to listen and forward events.
This keeps components simple and communication clear.