Svelte: Sharing Data Between Components


There is a few ways to pass the props from component to component.

  • Use getContext and getContext from svelte.
			
		
	// +layout.svelte
	import {setContext} from 'svelte';
	const routes = {
		main:"/",
		about:"/about",
		service:"/service",
		team:"/team",
		contact:"/contact",
		blog:"/blog"
	}
	setContext('routes', routes);

	// Header.svelte
	import {getContext} from 'svelte';
	const routes = getContext('routes');
	
			
		
  • Use context module and stores.
			
		
// +layout.svelte
<script context="module">
    import { writable } from 'svelte/store';
    export let routes = writable([]);
</script>
<script>
	const routes = {
	main:"/",
	about:"/about",
	service:"/service",
	team:"/team",
	contact:"/contact",
	blog:"/blog"
}
</script>

// Header.svelte
<script>
    import { routes } from './+layout.svelte';
</script>
	
			
		
  • Passing down to hierarchy.
			
		
// +layout.svelte
<script>
import Header from './Header.svelte';
import Footer from './Footer.svelte';
const routes = {
	main:"/",
	about:"/about",
	service:"/service",
	team:"/team",
	contact:"/contact",
	blog:"/blog"
}
</script>
	
<Header {routes} />
<slot {routes} />
<Footer {routes} />

// Header.svelte
<script>
	export let routes;
</script>

// Footer.svelte
<script>
	export let routes;
</script>