Native Web Components playground

Nova v3.38.0

Preview

Web Components

The active page

How activePath marks the current item, how parents of sub-items behave, and how to connect the sidebar to a router.

Give the sidebar the current location in activePath. It marks the item or sub-item whose link points there, and keeps doing so when the location, the links or the items change. You don't set active on any item yourself.

Nested

  • The match is exact. activePath is compared with the link's href attribute as it is rendered. /reports does not match /reports/2024, /reports/ or /reports?tab=1.
  • Items without an href are left alone. That includes parents that use a <span> as their label. You can set active on those yourself.
  • Without activePath the sidebar marks nothing. Set active on items yourself if you prefer. Clearing activePath later removes only the highlights it had set.
  • Changes are followed. A new activePath, a link that gets another href and items added later are all matched right away.

Because the comparison uses the rendered href, pass the path in the same form your links have. A router that serves the application below a base path renders that base path into the href, so it has to be part of activePath too.

Parents and sub-items#

A parent is not marked because one of its sub-items is. What you see depends on whether the active sub-item is visible:

StateWhat is highlighted
Parent openThe sub-item
Parent closedThe parent
Sidebar collapsed to the icon railThe parent

Try it in the example above: close Projects while Atlas is the current page. A parent that is active in its own right, because its own link matches or you set active, stays active in every state.

Keep a section active on deeper routes#

The exact match means /projects/42/settings marks nothing if the sidebar only links to /projects. Map the location to the entry it belongs to before you pass it on:

tsconst sections = ['/dashboard', '/projects', '/settings'];

function sectionOf(pathname: string) {
  return (
    sections.find(
      (section) => pathname === section || pathname.startsWith(`${section}/`),
    ) ?? pathname
  );
}

Connect it to a router#

Without a router, read the location and update the property when it changes:

tsconst sidebar = document.querySelector('nv-sidebar');
const update = () => (sidebar.activePath = location.pathname);

window.addEventListener('popstate', update);
update();

What assistive technology gets#

The active item and the active sub-item carry aria-current="page". A collapsible parent never does, also when it is highlighted for a hidden sub-item: the current page is inside it, and it exposes aria-expanded instead.