Passing data between sibling components in Svelte

4.4k views Asked by At

How to pass data (ex: Navbar Title) to a component used in the parent element?

<!-- _layout.svelte -->
<script>
  import Nav from "../components/Nav.svelte";
  let navTitle = "MyApp";
</script>

<Nav {navTitle}/>
<slot />
<!-- Nav.svelte -->
<script>
  export let navTitle = "";
</script>
<h1>{navTitle}</h1>
<!-- Login.svelte -->
How to pass navTitle value from here to Nav.svelte?

To clarify, this needs to be scalable and to work on page load/transition for all routes of an SPA using Routify, preferably providing a default value and be able to have HTML value:

<!-- Article.svelte -->
<!-- User.svelte -->
navTitle is '<a href="/user">My Account </a>'
<!-- Comment.svelte -->
3

There are 3 answers

4
Stephane Vanraes On BEST ANSWER

The easiest way to share data across components is to use stores as described in the docs

Your setup for that would be

<!-- Nav.svelte -->
<script>
  import { navTitle } from './store.js'
</script>
<h1>{$navTitle}</h1>
<!-- Login.svelte -->
<script>
  import { navTitle } from './store.js'

  navTitle.set('...')
</script>
<!-- store.js -->
import { writable } from 'svelte/store'

export const navTitle = writable('')
1
grohjy On

You can pass a function to Login.svelte component

<script>
  import Nav from "./Nav.svelte";
  import Login from "./Login.svelte"
  let navTitle = "MyApp";
  const onlogin= (v)=>navTitle = v
</script>
<Login {onlogin}/>
<Nav {navTitle}/>

And call the passed function in the Login.svelte

<script>
export let onlogin
</script>

<p on:click={()=>onlogin("Logged in")}>
  click me to login
</p>

Here is the REPL: https://svelte.dev/repl/f1c8777df93f414ab26734013f2c4789?version=3

There are other (better) ways to do this like:

  • Custom events with createEventDispatcher
  • Stores
  • Context (setContext, getContext)
  • Multiple Redux-adaptations for svelte
0
Ac Hybl On

Check out this example in case you need to communicate between sibling elements but you need the shared data to be specific to each group of sibling components.