An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
Simple Page Transitions with SvelteKit
Demo: https://sveltekit-page-transitions.netlify.app/
Source code: https://github.com/evanwinter/sveltekit-page-transitions
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.
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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To