EDOARDO CASELLA

Freelance web developer


Blog > Call parent component from child component in SvelteKit

Call parent component from child component in SvelteKit

SvelteKit Information technology
Posted Tue Nov 30 2021
Updated Tue Nov 30 2021

Sooner or later you need to call the function of a parent component from a child component, for example to pass data. I think in SvelteKit it is perhaps the easiest way I have focused.

To be able to call a parent function you must first of all obviously have a parent component, which instantiates a child component, as in this example.

// Parent Component
<script>
import ChildComponent from 'myPath/ChildComponent.svelte';
</script>

<div>
   <ChildComponent></ChildComponent>
</div>

Once we have found ourselves in a similar situation, we can start developing the arguments. So I take the previous code and modify it a little.

// Parent Component
<script>
import ChildComponent from 'myPath/ChildComponent.svelte';

function parentFunctionToCall(arg) {
   console.log("Parent say: "arg);
}
</script>

<div>
   <ChildComponent onInputChange={(val) => parentFunctionToCall(val)}></ChildComponent>
</div>

Now let's see what the child component will contain.

// Child Component
<script>
export let onInputChange = null;
</script>

<div>
   <input type="text" on:keyup={(event) => onInputChange(event.target.value)} />
</div>

In this way SvelteKit is doing nothing but calling the function passed by the parent to each keyUp event of the input field, and we are also passing the value of "event.target.value" which will contain the letter that was pressed