How to send events from a child to parent in Svelte
📣 Sponsor
Event forwarding is used when a user triggers an event on a child component, which we want to handle in the parent component. It means we can say that specific elements have event capabilities, but we aren’t going to define them just yet. Let’s look at how it works
How Event forwarding in Svelte Works
Let’s look at an example. Suppose we have a component in Svelte which has two buttons - one is clickable, and the other is not. Let’s call this file Comp.svelte
<button on:click>
Click me, I am a button
</button>
<button>
I am unclickable. Ignore me.
</button>
Here we are saying that the first button has a valid on:click
event. That means we can differentiate which elements in a child component are actually clickable. This also applies to any other valid Svelte Event.
Now if we want to add an event to that button in our child component, we can do it in the parent! So let’s say we now have a Svelte page where we import Comp.svelte
. Since we indicated where the on:click
event should sit, we can add it straight onto the Comp
tag itself. By adding on:click={consoleTheUser}
, we say whenever the user clicks on our on:click
button, then run the consoleTheUser
function.
<script>
import Comp from './Comp.svelte';
const consoleTheUser = () => {
console.log('You clicked a button')
}
</script>
<Comp on:click={consoleTheUser} />
This means we can define child components that are totally abstracted from events. So if we have the same child components that should act differently on different pages, we can give them this flexibility. Now our event functions can sit in the parent, while the child component can hold the style and layout alone.
More Tips and Tricks for Svelte
- Each Logic in Svelte
- How to Create Components in Svelte
- Getting Started with Events in Svelte
- How if-else Logic works in Svelte
- How to Handle Reactivity in Svelte
- Creating your first Svelte App with SvelteKit
- How to send events from a child to parent in Svelte
- How to pass arguments to events like on:click in Svelte