Using Functions From Another Svelte Component

Published Feb 10, 2024

If you want to use a function from another Svelte component, export the function, and then you can bind the component in the parent.

video.svelte
<script>
  let { src, ...props } = $props()
  let videoEl

	export function play() {
		videoEl.play()
	}

	export function pause() {
		videoEl.pause()
	}
</script>

<video bind:this={videoEl} {...props}>
	<source {src} type="video/mp4">
</video>

Bind the component using Svelte’s bind: directive to get a reference to the component after which you can use the exported functions.

app.svelte
<script>
  import Video from './video.svelte'

  let videoComponent
</script>

<Video bind:this={videoComponent} src="video.mp4" controls />

<button onclick={() => videoComponent.play()}>
  Play
</button>

<button onclick={() => videoComponent.pause()}>
  Stop
</button>

This works the same regardless what Svelte version you’re using.

Support

If you want to support the content you're reading or watching on YouTube consider becoming a patreon starting low as 1$ per month.

Become a patreon
Subscribe For Updates
Found a mistake?

Every post is a Markdown file so contributing is simple as following the link below and pressing the pencil icon inside GitHub to edit it.

Edit on GitHub