user2670914
user2670914

Reputation: 75

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

Upvotes: 7

Views: 4958

Answers (3)

Ac Hybl
Ac Hybl

Reputation: 485

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.

Upvotes: 0

Stephane Vanraes
Stephane Vanraes

Reputation: 16411

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

Upvotes: 9

grohjy
grohjy

Reputation: 2149

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

Upvotes: 1

Related Questions