Search code examples
sveltesvelte-componentsvelte-storeroutify

Passing data between sibling components in Svelte


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

Solution

  • 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('')