Not long ago, I was working on creating an app, and I had this puzzle to solve: How do I figure out the current page's path and apply a CSS style to show it's active? It got a bit tricky because I was using Svelte Kit, and I needed those routes to be super responsive. Sure, I could've gone with regular JavaScript, but that felt a bit too wordy and not as snappy as I wanted it to be. Here's what I mean:
<script>
import { onMount } from 'svelte';
let current_url = '';
onMount(() => current_url = window.location.href);
</script>
<p>{current_url}</p>
But, you know, this wasn't exactly what I had in mind. So, I went on a little quest to find the solution I was after. And, well, since I couldn't seem to locate this solution anywhere else, I thought, why not share it right here? You never know, it might come in handy for someone else down the road. π
<script>
import { page } from '$app/stores';
let current_url = $page.url.pathname.split('/').filter(Boolean).pop() || '/';
</script>
<p>{current_url}</p>
This here might come in handy for those who are looking to grab that '/' path. Now, if that's not quite your thing, no worries, you can just breeze right past that '||' part in the code. It's all about making things work just the way you need them to! π
Now, let's get into it. It wouldn't be great if I left you hanging, right? You see, the code does its thing, and the 'current_url' is spot on as the current page. But, there's a little catch - it doesn't quite update when you hop from page to page. It only does its magic when you hit that refresh button. And here's where the fun begins - to make it all tick as it should, we've got a little trick up our sleeve (you could call it a hack, if you like). π
<script>
import { page } from '$app/stores';
import { afterUpdate } from 'svelte';
// Set the current URL
let current_url = $page.url.pathname.split('/').filter(Boolean).pop() || '/';
// Set it as soon as pages update
afterUpdate(() => {
current_url = $page.url.pathname.split('/').filter(Boolean).pop() || '/';
});
</script>
<p>{current_url}</p>
Now then, everything should be running smoothly, with no hiccups in sight. π
I really hope this comes in handy for you, especially if you were looking for something like this. For an updated version with even more information, check out my new article here:
Snag the Current URL in SvelteKit (2024 Edition)
Michael Amachree γ» Apr 25
Happy URL Snatching!
Top comments (1)
You can make it more concise by doing this: