Svelte Binding Variables Across Components

Watching for a change in the child component changing the parent component doesn't always have to be a store. A bound variable can do it.

svelte logo

Want to build a Svelte/SvelteKit site? Hire Me.

Passing Props

Passing props from parent to children is quite easy in Svelte. But the other way around is a little tricky.

I recommend using stores where it is completely necessary. For simpler cases, we can use component binding.

Component Binding

Consider this design where there are 3 components one indide the other.

svelte components props binding

We can bind component props so that they maintain the same state across.

Header.svelte

<script>
  import Nav from "./Nav.svelte";

  export let isDarkMode = false;
</script>

<Nav bind:isDarkMode />

Now since the variable isDarkMode is bound to Nav, any changes to it in the <Nav /> will reflect in the <Header />.

Nav.svelte

<script>
  import ShowCurrentMode from "./ShowCurrentMode.svelte";

  export let isDarkMode;
</script>

<button on:click={() => isDarkMode = !isDarkMode} >Switch</button>

<ShowCurrentMode bind:isDarkMode />

This can be bound to multiple components inside <Nav />.

ShowCurrentMode.svelte

<script>
  export let isDarkMode;
</script>

<p>Current mode is {isDarkMode ? "Dark" : "Light"}</p>

Now, all three components will have the variable isDarkMode in the same state. Any change in its state in the <Nav /> will change reflect in the parent component <Header /> and also at the child component <ShowCurrentMode />.

Find related articles

Let's discuss on Twitter