javascript / intermediate
Snippet
Component References with bind:this
While props are the primary way to communicate down, 'bind:this' allows a parent to obtain a reference to a child component instance. This is useful for calling methods exported by the child via 'export const someMethod = ...', though it should be used sparingly.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
<script>import Child from './Child.svelte';let childInstance;function handleClick() {childInstance.externalMethod();}</script><Child bind:this={childInstance} /><button on:click={handleClick}>Call Child</button>
svelte
Breakdown
1
bind:this={childInstance}
Assigns the instantiated component object to the local variable 'childInstance'.