Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
How to set menu item to active in sveltekit app

I have been working on a sveltekit application and recently ran into an issue with my main navigation menu. when the application is loaded or refreshed the current menu item that corresponds with the current URL is not set to active. (i.e. menu item 'Home' would have URL of '/') I had a hard time finding anything useful online demonstrating how to set this up, but I have a working solution and thought I'd document it for others. It is very simple at the moment.

I have a nav.json file where I define any menus within my application, making it easy to organize menus. I import that at the top of the file and store it in an array for use later.

import menuObj from '../nav/nav.json';

let sidebar = menuObj.menus[0].items;

onMount() is just getting the current path when the nav component is loaded, and only runs once for me.

then - using <svelte:window on:click={handlePageClick}/> we can listen to any clicks on the page.

In the handlePageClick(e) method we pass the on:click event. Using that event we can capture the current pathname of the URL. this allows us to check the pathname against our item.path which is defined in the nav.json file I've imported and extracted using the #each method in our html. On the <a> we can set the class to active if the items route matches the current path.

here is the full implementation

<script>
    import menuObj from '../nav/nav.json';
    import {onMount} from "svelte";

    let path;
    let sidebar = menuObj.menus[0].items;

    onMount(() => {
        path = window.location.pathname;
    })

    function handlePageClick(e) {
        path = e.view.location.pathname;
    }

</script>

<svelte:window on:click={handlePageClick}/>
<nav class="sidebar">
    {#each sidebar as item, i}
        <a href={item.route} id="sidebar-menu-item-{item.id}" 
           class={path === item.route ? "item active" : "item"}
        >
            <i id="sidebar-menu-item-{item.id}-i" class="{item.icon}"></i>
        </a>
    {/each}
</nav>

I haven't found any drawbacks to this yet. I will update this question if I find anything.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It's not really a question, but I will add an answer anyway because your method is not necessary, SvelteKit already has a built in system for this:

<script>
 import { page } from '$app/stores';
</script>

<a href={item.route} class="item" class:active={$page.url.pathname == item.route}>
 ...
</a>

page is a store like object that among other things hold the current path, it will automatically be updated with the new path

as a bonus:

class:active is an easy shorthand, removing that ternary expression there.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda