Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example of how to add an active class #39

Open
lukx33 opened this issue Jan 3, 2025 · 1 comment
Open

Example of how to add an active class #39

lukx33 opened this issue Jan 3, 2025 · 1 comment

Comments

@lukx33
Copy link

lukx33 commented Jan 3, 2025

  <nav>
    <a use:route href="/">start</a>
    <a use:route href="/test" >test</a>
    <a use:route href="/test2" >test 2</a>
  </nav>

Is there any easy way to add class="active" for the current address/router?

@lukx33
Copy link
Author

lukx33 commented Jan 3, 2025

Something like this would be awesome.

To type Route I added label, path2 and isCurrent.
This allows me to use the routes array to create menu.
At the same time, I can immediately use isCurrent to mark which position is current/active.

path could be called pathToMatch.
path2 could be called pathToOpen.

Of course, the logic I wrote in my pre function would need to be moved to the Instance code.

<script lang="ts">
  import "./app.css";
  import { route, Router, type Route } from "@mateothegreat/svelte5-router";

  import Home from "./routes/Home.svelte";
  import Test from "./routes/Test.svelte";

  const routes: Route[] = $state([
    {
      label: "start",
      path2: "/",
      path: "^/$",
      component: Home,
      isCurrent: false,
    },
    {
      label: "test",
      path2: "/test",
      path: "/test",
      component: Test,
      isCurrent: false,
    },
  ]);

  async function pre(route: Route): Promise<Route> {
    for (const r of routes) {
      if (r.path == route.path) {
        r.isCurrent = true;
      } else {
        r.isCurrent = false;
      }
    }

    return route;
  }
</script>

<main>
  <nav>
    {#each routes as r}
      <a use:route href={r.path2} class={r.isCurrent ? "active" : ""}> {r.label}</a>
    {/each}
  </nav>

  <Router {pre} {routes} />
</main>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant