Projects Blog

How to send events from parent to children in Svelte

To listen for child dispatched events from any parent element, we know we can use the createEventDispatcher function. However, that is not the focus of this post.

In some cases, we want to listen for a parent dispatched event from a child.

This can be achieved in a few ways, such as using props or methods drilling. By the way, I prefer to use a event-driven pattern.

This pattern offers several advantages compared to drilling:

Code example

We can use the native Web API dispatchEvent and addEventListener.

Just dispatch a CustomEvent in the parent component, or where you need.

Parent.svelte
<script>
function handleClick() {
const event = new CustomEvent('message', { detail: 'Hello!' });
document.dispatchEvent(event);
}
</script>
<button type="button" on:click={handleClick}> Parent dispatching an event </button>

Then, listen to that CustomEvent in the child element using addEventListener.

Child.svelte
<script>
document.addEventListener('message', (e) => {
alert(`Message received: ${e.detail}`);
});
</script>
<p>Child listening to the event</p>

With this easy pattern, you can easily listen for child dispatched events from any parent element, ensuring that the project remains effortlessly scalable


I hope you found this article useful.

Happy coding! 🚀

Related posts