0
0
Svelteframework~5 mins

Component events (createEventDispatcher) in Svelte

Choose your learning style9 modes available
Introduction

Component events let parts of your app talk to each other. createEventDispatcher helps a child component send messages to its parent.

You want a button component to tell its parent when it is clicked.
A form component needs to send the entered data back to the main app.
A custom input component should notify the parent when its value changes.
You want to keep components separate but still let them communicate easily.
Syntax
Svelte
import { createEventDispatcher } from 'svelte';

const dispatch = createEventDispatcher();

dispatch('eventName', detailObject);

Always import createEventDispatcher from 'svelte'.

Use dispatch to send an event with a name and optional data.

Examples
Sends a simple event named 'hello' without extra data.
Svelte
import { createEventDispatcher } from 'svelte';

const dispatch = createEventDispatcher();

dispatch('hello');
Sends an event 'greet' with a user object as data.
Svelte
import { createEventDispatcher } from 'svelte';

const dispatch = createEventDispatcher();

const user = { name: 'Anna' };
dispatch('greet', user);
Sample Program

The child component sends a 'message' event with text when the button is clicked. The parent listens for this event and shows the message.

Svelte
<!-- Child.svelte -->
<script>
  import { createEventDispatcher } from 'svelte';
  const dispatch = createEventDispatcher();

  function sendMessage() {
    dispatch('message', { text: 'Hello from child!' });
  }
</script>

<button on:click={sendMessage} aria-label="Send message to parent">Send Message</button>


<!-- Parent.svelte -->
<script>
  import Child from './Child.svelte';

  let received = '';

  function handleMessage(event) {
    received = event.detail.text;
  }
</script>

<main>
  <Child on:message={handleMessage} />
  <p>Received message: {received}</p>
</main>
OutputSuccess
Important Notes

Event names are case-sensitive and usually lowercase.

Use event.detail in the parent to get data sent by the child.

Always add accessible labels like aria-label for buttons.

Summary

createEventDispatcher lets child components send events to parents.

Use dispatch('eventName', data) to send messages.

Parents listen with on:eventName and get data from event.detail.