In Svelte 5, the way components communicate with each other has changed significantly compared to previous versions. The key concept is using callback props instead of the traditional event system. Let me break this down for you:
In Svelte 4, you would use createEventDispatcher
to emit events from a child component, and the parent would listen to those events using on:eventname
. For example:
<!-- Child.svelte -->
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function handleClick() {
dispatch('message', { text: 'Hello from child!' });
}
</script>
<button on:click={handleClick}>Send Message</button>
<!-- Parent.svelte -->
<script>
import Child from './Child.svelte';
function handleMessage(event) {
console.log(event.detail.text); // "Hello from child!"
}
</script>
<Child on:message={handleMessage} />
In Svelte 5, createEventDispatcher
is deprecated. Instead, you use callback props. Here's how it works:
<!-- Child.svelte -->
<script>
// Accept a callback prop from the parent
let { onMessage } = $props();
function handleClick() {
// Call the callback prop with data
onMessage?.('Hello from child!');
}
</script>
<button onclick={handleClick}>Send Message</button>
<!-- Parent.svelte -->
<script>
import Child from './Child.svelte';
function handleMessage(text) {
console.log(text); // "Hello from child!"
}
</script>
<!-- Pass the callback function as a prop -->
<Child onMessage={handleMessage} />
onMessage
instead of just onClick
).onMessage?.()
) to avoid errors if the parent doesn't provide the callback.You can pass multiple callback props for different actions:
<!-- Child.svelte -->
<script>
let { onMessage, onError } = $props();
function handleClick() {
if (Math.random() > 0.5) {
onMessage?.('Success!');
} else {
onError?.('Something went wrong!');
}
}
</script>
<button onclick={handleClick}>Try Action</button>
<!-- Parent.svelte -->
<script>
import Child from './Child.svelte';
function handleMessage(text) {
console.log(text); // "Success!"
}
function handleError(text) {
console.error(text); // "Something went wrong!"
}
</script>
<Child onMessage={handleMessage} onError={handleError} />
In Svelte 5, callback props are the recommended way to communicate between child and parent components. They replace the old event system and provide a simpler, more flexible approach. By passing functions as props, you can easily handle actions and data flow between components.
Let me know if you have further questions!