#Would like some help in 'adding class to the currently active page' functionality

13 messages · Page 1 of 1 (latest)

analog summit
#

I want to visually highlight the currently active page in the navigation menu. I have this code with me right now

---
export interface Props {
  activeNav?: "courses" | "ebooks" | "cheatsheets" | "articles";
}
const { activeNav } = Astro.props;
---
<li>
        <a href="/courses" class={activeNav === "courses" ? "active" : ""}>
          Courses
        </a>
      </li>
      <li>
        <a href="/cheatsheets" class={activeNav === "cheatsheets" ? "active" : ""}>
          Cheatsheets
        </a>
      </li>
      <li>
        <a href="/ebooks" class={activeNav === "ebooks" ? "active" : ""}>
          Ebooks
        </a>
      </li>
      <li>
        <a href="/articles" class={activeNav === "articles" ? "active" : ""}>
          Articles
        </a>
      </li>
hollow lake
#

@analog summit Have you tried adding this to a page yet?

#

It looks like astro-paper uses this navigation on individual pages instead of in a layout so for this component you would have to do something like this on each page```
// src/pages/about
<Header activeNav="about" />

// src/pages/tags
<Header activeNav="tags" />

...

analog summit
#

Alright, so just to check I added activeNav attribute to header with courses and the active class was inserted

#

yeah, but it seems I'd have to change the structure of my project

#

to inherit this functionality

#

I have a BaseLayout component that has a slot and that slot carries page like courses

hollow lake
#

I would improve this by using Astro.url.pathname ```jsx

export interface Props {
pathname?: string;
}
const {
pathname = Astro.url.pathname
} = Astro.props;

<ul>
<li>
<a href="/cheatsheets" class={pathname === "/cheatsheets" ? "active" : ""}>
Cheatsheets
</a>
</li>
<li>...</li>
</ul>

analog summit
#

Hey, it works flawlessly! Thank you so much, Bryce!

#

You've been a great help!

analog summit
viscid saffron
#

Works well on my browser