0
0
Svelteframework~30 mins

Component events (createEventDispatcher) in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Component events with createEventDispatcher in Svelte
📖 Scenario: You are building a simple Svelte app where a child component sends a message to its parent when a button is clicked.
🎯 Goal: Create a child component that dispatches a custom event using createEventDispatcher. The parent component listens to this event and updates a message on the screen.
📋 What You'll Learn
Create a child component with a button
Use createEventDispatcher in the child to send a custom event named notify
In the parent component, listen for the notify event from the child
Update a message in the parent when the event is received
💡 Why This Matters
🌍 Real World
Component events let parts of your app talk to each other without being tightly connected. For example, a form component can tell its parent when it is submitted.
💼 Career
Understanding component events is key for building interactive user interfaces in Svelte, a popular modern web framework used in many companies.
Progress0 / 4 steps
1
Create the child component with a button
Create a Svelte component file named Child.svelte. Inside it, add a <button> element with the text Click me.
Svelte
Need a hint?

Use the <button> tag and put the text inside it.

2
Add createEventDispatcher and prepare to dispatch event
In Child.svelte, import createEventDispatcher from 'svelte'. Then create a dispatcher variable by calling createEventDispatcher().
Svelte
Need a hint?

Use import { createEventDispatcher } from 'svelte'; and then const dispatch = createEventDispatcher();

3
Dispatch the 'notify' event when button is clicked
In Child.svelte, add a click event handler to the <button> that calls dispatch('notify') when clicked.
Svelte
Need a hint?

Add on:click={() => dispatch('notify')} to the button.

4
Create parent component to listen and update message
Create a Parent.svelte component. Import Child component. Add a message variable initialized to Waiting for event.... Render <Child /> and listen for the notify event with on:notify. When the event fires, update message to Event received!. Display {message} below the child.
Svelte
Need a hint?

Use on:notify on the <Child /> tag to update message.