Svelte Breadcrumbs Made Easy

July 14, 2023

Svelte Breadcrumbs Made Easy

Table of Contents

Creating the Segments

Making breadcrumbs base on routes is straightforward. In SvelteKit, +page.server.ts, +page.ts, +layout.server.ts, and +layout.ts load functions have an event parameter with an async parent() method that returns data from parent +layout.server.ts and +layout.ts load functions.

By placing a breadcrumbs array in the root layout, you can use event.parent() and Array.concat to append breadcrumbs at each route segment which requires a breadcrumb. And you can use data from that route segment to make the breadcrumb value and href dynamic.

Here is an example used on my Adventurers League Log Sheet app.

Root layout

First breadcrumb segment

Next breadcrumb segment with param

Now the resulting array in data.breadcrumbs for /characters/[characterId] is:

js
[
  { name: 'Characters', href: '/characters' },
  { name: 'Rimurus', href: '/characters/cl7gfkggq002009mluw41peqd' }
]

The Breadcrumbs Component

From there, you can create a breadcrumbs component like this: