This content originally appeared on DEV Community and was authored by Evan Winter
Overview
Create a
<PageTransition />
component which transitions out and back in when page navigation occurs.Wrap your layout file's
<slot />
(the current route's content) in the<PageTransition />
component.
The code: https://github.com/evanwinter/sveltekit-page-transitions
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="/">Home</a>
<a href="/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.
This content originally appeared on DEV Community and was authored by Evan Winter
Evan Winter | Sciencx (2021-05-14T19:09:54+00:00) Simple Page Transitions with SvelteKit. Retrieved from https://www.scien.cx/2021/05/14/simple-page-transitions-with-sveltekit/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.