0
0
Svelteframework~30 mins

Event forwarding in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Event Forwarding in Svelte
📖 Scenario: You are building a simple user interface with two components: a Button component and a App component. The Button component will emit a click event, and the App component will listen to that event.To keep your code clean, you want the Button component to forward the click event it receives to its parent App component.
🎯 Goal: Create a Button.svelte component that forwards the click event to its parent. Then use this component inside App.svelte and handle the forwarded event to update a counter.
📋 What You'll Learn
Create a Button.svelte component with a button element
Forward the click event from Button.svelte to its parent
Create an App.svelte component that uses Button
Handle the forwarded click event in App.svelte to increment a counter
Display the current count in App.svelte
💡 Why This Matters
🌍 Real World
Event forwarding is useful when building reusable UI components that need to communicate user actions to parent components without exposing internal details.
💼 Career
Understanding event forwarding is important for frontend developers working with component-based frameworks like Svelte, React, or Vue to build clean and maintainable code.
Progress0 / 4 steps
1
Create the Button component with a button element
Create a Svelte component file named Button.svelte. Inside it, write a <button> element with the text Click me.
Svelte
Need a hint?

Start by writing a simple button element with the text 'Click me' inside your Button.svelte file.

2
Forward the click event from Button component
In Button.svelte, import createEventDispatcher from 'svelte'. Create a dispatcher with const dispatch = createEventDispatcher(). Add an event handler to the <button> that calls dispatch('click') when the button is clicked.
Svelte
Need a hint?

Use createEventDispatcher to forward the click event from the button to the parent component.

3
Use Button component in App and handle forwarded click
Create App.svelte. Import Button from './Button.svelte'. Create a variable count initialized to 0. Add the <Button /> component with an event listener on:click that increments count by 1.
Svelte
Need a hint?

Import the Button component and use it. Listen for the click event to update the count variable.

4
Display the click count in App component
In App.svelte, below the <Button />, add a paragraph element <p> that shows the text Clicked {count} times to display the current count.
Svelte
Need a hint?

Use a paragraph element to show how many times the button was clicked by displaying the count variable.