RGB logo

RGB Studios.org

A web development company

July 20, 2023

Page Transitions in Svelte Kit

Justin Golden

webdev
svelte
svelte kit
Photo credit @juliakadel on Unsplash

Pages in Svelte Kit are similar to components, and they’re mounted and unmounted.

We can use transition:, in:, and out: on them as well (learn more about transitions in svelte kit).


Steps

There are just two steps to creating page transitions with svelte kit!

(to see the thought process explained, as well as more detail on custom transitons, check the video linked below)

Step 1: Setting up url from your server

In your routes/+layout.server.js file (create one if you don’t have one), export the url.pathname:

export const load = async ({ url }) => {
	return {
		url: url.pathname
	};
};

(if you already have a load function, add url: url.pathname to the returned object and extract url from the parameter if you don’t already use it)

Step 2: Creating the page transitions

In your routes/+layout.svelte file, import the transition you want to use. I’ll be importing fade:

import { fade } from 'svelte/transition';

Next, we want to be able to recieve the data from our server file:

export let data;

Last, we will run the transition when data.url changes:

{#key data.url}
  <div in:fade={{ duration: 250, delay: 250 }} out:fade={{ duration: 250 }}>
    <slot />
  </div>
{/key}

Make sure you set your in transition delay to be the same as the out transition duration.

Related Video

Check out this video on svelte kit page transitions by Joy of Code who has a lot of cool Svelte content!


More Blog Articles
  Share   Tweet   Pin   Share   Post   Post   Share   Email