Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 14, 2021 07:09 pm GMT

Simple Page Transitions with SvelteKit

Demo: https://sveltekit-page-transitions.netlify.app/
Source code: https://github.com/evanwinter/sveltekit-page-transitions

Overview

  1. Create a <PageTransition /> component which transitions out and back in when page navigation occurs.

  2. Wrap your layout file's <slot /> (the current route's content) in the <PageTransition /> component.

Step 1: Creating the <PageTransition /> component

Create a component file at src/lib/components/PageTransition.svelte.

<!-- PageTransition.svelte --><script>  import { fly } from "svelte/transition"  export let refresh = ""</script>{#key refresh}  <div in:fly={{  x:-5, duration: 500, delay: 500 }}       out:fly={{ x: 5, duration: 500             }}>    <slot />  </div>{/key}

When the value of refresh changes, the component will destroy and recreate itself, executing the in:fly and out:fly transitions at those steps.

As far as the user is concerned, these things happen almost simultaneously so we need a delay on the in transition so that it starts after the old route has transitioned out.

Step 2: Using the <PageTransition /> component

Create a layout file at src/routes/__layout.svelte.

<!-- __layout.svelte --><script>  import PageTransition from "$lib/components/PageTransition.svelte"  export let key</script><!-- 1. Assign current route's path to `key` prop --><script context="module">  export const load = async ({ page }) => ({    props: {      key: page.path,    },  })</script><div>  <nav>    <a href="https://dev.to/">Home</a>    <a href="https://dev.to/about">About</a>  </nav>  <!-- 2. Pass `key` prop to the component so it knows when to transition -->  <PageTransition refresh={key}>    <slot />  </PageTransition></div>

On page load, we get the page's path with the load function. So when the page changes, we get a new key prop returned by the load function.

That key prop is passed to the PageTransition component, so when a change is detected (e.g. page navigation occurred), the component does the out and in transitions.


Original Link: https://dev.to/evanwinter/page-transitions-with-svelte-kit-35o6

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To