Svelte — How to Call Functions in Child Components

sobPilot
2 min readSep 14, 2020

Svelte is so Vanella JavaScript that I totally missed an easy way to make use of functions in child components.

I’ve often wanted to call a function to do things like show popups, call APIs, and compute values from a child component. In the beginning, I did this by watching a variable in the component with $: and calling the internal function on a change. For example, when a variable “show” passed as a prop changed from false to true I would popup a modal. I never liked doing this but it worked.
Using the “bind:” attribute in a Svelte component seems to assign anything to the variable. So, in the parent component simply bind a variable to an exported function or object in the child component.

IN THE CHILD COMPONENT CREATE AN OBJECT

<script>
export const b5modal = {
toggle() {
show = !show
},
show() {
show = true
console.log("sob--: show -> show", show)
},
hide() {
show = false
console.log("sob--: hide -> show", show)
},
showHide(isShow) {
isShow ? (show = true) : (show = false)
console.log("sob--: showHide -> isShow", isShow)
},
}
</script>

IN THE PARENT COMPONENT BIND THE CHILD OBJECT TO A LOCAL VARIABLE

<script>
import B5modal from "../components/b5ui/B5modal.svelte"
let modal
</script
<B5modal bind:show={showModal} bind:b5modal={modal} size="lg">
<div slot="header">
<h5>{edt.heading}</h5>
Size = lg
</div>
<div>{edt.body}</div>
</B5modal>

CALL THE CHILD FUNCTION FROM THE PARENT

<button on:click={() => modal.showHide(true)} class="btn btn-primary mb-2">Show Modal</button>

Now go make your components much smarter by adding function libraries to them!

--

--

sobPilot
sobPilot

Written by sobPilot

A Pilot and Developer. I can't figure out if piloting pays for my development or development pays for my piloting.

Responses (1)