0
0
Svelteframework~5 mins

Event forwarding in Svelte

Choose your learning style9 modes available
Introduction

Event forwarding lets a component pass events it receives up to its parent. This helps keep components simple and reusable.

You build a button component that should act like a normal button and send click events to its parent.
You create a custom input component and want to forward input or change events to the parent form.
You wrap a third-party component and want to pass its events up without extra code.
You want to keep your components decoupled but still allow communication through events.
Syntax
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.

Examples
Forward the click event from the Button component to the parent.
Svelte
<Button on:click />
Forward the input event from a custom input component.
Svelte
<CustomInput on:input />
Forward a custom event named customEvent from the child.
Svelte
<ChildComponent on:customEvent />
Sample Program

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.

Svelte
<!-- 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} />
OutputSuccess
Important Notes

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.

Summary

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.