Svelte Search

About

How to communicate events between child and parent components in svelte 5?

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:


The Old Way (Svelte 4 and Earlier)

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} />

The New Way (Svelte 5)

In Svelte 5, createEventDispatcher is deprecated. Instead, you use callback props. Here's how it works:

  1. Child Component: Instead of emitting events, the child accepts callback functions as props.
  2. Parent Component: The parent passes functions as props to the child, which the child can call when needed.

Example: Child Component

<!-- 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>

Example: Parent Component

<!-- 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} />

Why Use Callback Props?

  1. Simplicity: Callback props are just functions, making them easier to understand and use.
  2. Flexibility: You can pass any function as a prop, not just event handlers.
  3. Consistency: Props are the primary way components communicate in Svelte 5, so this approach aligns with the overall design philosophy.

Key Points to Remember

  • Callback Naming: Use descriptive names for callback props (e.g., onMessage instead of just onClick).
  • Optional Callbacks: Use optional chaining (onMessage?.()) to avoid errors if the parent doesn't provide the callback.
  • No Event Bubbling: Unlike the old event system, callback props don't bubble. Each component must explicitly pass callbacks to its children.

Advanced Example: Multiple Callbacks

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} />

Summary

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!