Svelte Component Events

A component event lets a child component send a message up to its parent. This flow works in the opposite direction from props, since props travel down while component events travel up.

Why Component Events Matter

A child component often needs to notify its parent about something that happened inside it, such as a button click or a form submission. Component events give the child a clear way to raise that notification without directly changing the parent's data itself.

Creating An Event Dispatcher

<!-- LikeButton.svelte -->
<script>
  import { createEventDispatcher } from "svelte";

  const dispatch = createEventDispatcher();

  function handleClick() {
    dispatch("liked");
  }
</script>

<button on:click={handleClick}>Like</button>

The dispatch function fires a custom event named liked whenever a visitor clicks the button. The component itself does not decide what happens next, it only announces that a click occurred.

Listening For The Event In A Parent

<!-- App.svelte -->
<script>
  import LikeButton from "./LikeButton.svelte";
  let likeCount = 0;

  function handleLike() {
    likeCount = likeCount + 1;
  }
</script>

<LikeButton on:liked={handleLike} />
<p>Total likes: {likeCount}</p>

The parent listens for the liked event using the same on: syntax used for native browser events. Every time the child dispatches liked, the parent runs handleLike and increases the count shown on the page.

Component Event Flow Diagram

LikeButton.svelte (Child)          App.svelte (Parent)
----------------------              ----------------------
Visitor clicks button
        |
        v
dispatch("liked")   ------------->  on:liked={handleLike}
                                            |
                                            v
                                    likeCount increases

Sending Extra Data With An Event

<script>
  function handleClick() {
    dispatch("liked", { itemId: 42 });
  }
</script>
<script>
  function handleLike(event) {
    console.log(event.detail.itemId);
  }
</script>

<LikeButton on:liked={handleLike} />

The second argument passed to dispatch travels along with the event, arriving inside event.detail on the parent's side. This pattern lets a child share extra context alongside the notification itself.

Forwarding Events Through Multiple Layers

A component sitting between a deeply nested child and the top-level parent can forward an event upward without writing a separate handler, using a shorthand syntax.

<LikeButton on:liked />

Writing on:liked without a value forwards the event straight up to whatever component sits above the current one, useful for passing events through a chain of components.

A Layman Analogy

Think of a component event as a chain of walkie-talkies. A worker on the ground floor presses a button and speaks into their radio, matching a child dispatching an event. A supervisor upstairs, matching the parent, listens on the same channel and reacts to the message.

Naming Events Clearly

Choosing a clear, action-based name for a dispatched event makes a component easier to understand for anyone reading the code later. Names like liked, submitted, or deleted describe exactly what happened, while vague names like update or change leave the reader guessing about the actual action.

Multiple Events From One Component

A single component can dispatch several different named events, each tied to a different action a visitor might take.

<script>
  import { createEventDispatcher } from "svelte";
  const dispatch = createEventDispatcher();
</script>

<button on:click={() => dispatch("approved")}>Approve</button>
<button on:click={() => dispatch("rejected")}>Reject</button>

The parent listens for approved and rejected separately, running different logic depending on which button a visitor actually clicked.

Key Points

  • Component events let a child notify its parent about something that happened
  • The createEventDispatcher function creates a dispatch tool inside a component
  • A parent listens using the same on: syntax used for native browser events
  • Extra data travels with an event through the detail property

Leave a Comment

Your email address will not be published. Required fields are marked *