Using Callback Functions as Props in Svelte
Introduction to Callback Functions in Svelte
In the previous lesson, you learned how to pass data from a parent component to a child component using props. This is a powerful way to share information between components, but what if the child component needs to communicate back to the parent? This is where callback functions come into play.
A callback function is a function passed from a parent component to a child component, allowing the child to "call back" to the parent when a specific event occurs. Think of it like this: the parent component (the manager) gives the child component (the employee) a task (the callback function) to execute. When the child completes the task, it notifies the parent by calling the function.
In this lesson, you’ll learn how to pass callback functions as props and use them to enable communication between parent and child components. This builds on your knowledge of props and takes component communication to the next level.
Passing Callback Functions as Props
To pass a callback function as a prop, you first define the function in the parent component. Then, you pass it to the child component just like any other prop. Let’s start with a simple example where the parent passes a console.log function to the child.
In this example:
- The parent component defines a
logMessagefunction that logs a message to the console. - The parent passes this function to the child component as a prop named
logHandler. - The child component receives the
logHandlerprop and uses it in anonclickevent. When the button is clicked, the child callslogHandlerwith the message"Hello from child!".
When you run this code and click the button, the message "Hello from child!" will appear in the console. This demonstrates how a child component can trigger a function defined in the parent component.
Triggering Callback Functions in Child Components
Now that you know how to pass a callback function as a prop, let’s explore how to trigger it in the child component. In Svelte, you can use events like onclick to call the callback function when a specific action occurs.
Here’s an example where the child component triggers the parent’s callback function when a button is clicked:
In this example:
- The parent component defines a
handleClickfunction that logs a message to the console. - The parent passes this function to the child component as a prop named
clickHandler. - The child component receives the
clickHandlerprop and uses it in anonclickevent. When the button is clicked, the child callsclickHandlerwith the message"Button clicked in child!".
When you run this code and click the button, the message "Button clicked in child!" will appear in the console. This shows how the child component can notify the parent component of an event by calling the callback function.
