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.
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 />
.