vaadin / router

Small and powerful client-side router for Web Components. Framework-agnostic.
https://vaadin.com/router
Apache License 2.0
425 stars 51 forks source link

Styled router links #49

Open vlukashov opened 6 years ago

vlukashov commented 6 years ago

As a developer I want to have an easy way to style differently the navigation link that leads to the currently active route in order to support the common UX pattern in navigation menus.

DoD:

The common DoD applies.

aress31 commented 4 years ago

+1 for the feature!

vlukashov commented 4 years ago

While there is no out-of-the-box 'active' links highlighting, here is a small example how to implement that in the app: https://glitch.com/edit/#!/highlight-current-nav-link?path=views%2Fmain-layout.js%3A19%3A3

This demo shows a navigation menu and highlights the currently active link. Generally, I see two approaches to implement this:

This demo uses the latter. On every location change it iterates over the list of all navigation tabs until it finds the first that matches the current URL, and then selects that as the active item in the <vaadin-tabs> container:

this.menuTabs = [
  {route: '/', name: 'Home'},
  {route: '/sam', name: 'User profile page'},
  {route: '/gibberish/not/name', name: '404 page'},
];

const isCurrentLocation = route => router.urlForPath(route) === this.location.getUrl();
const index = this.menuTabs.findIndex((menuTab) => isCurrentLocation(menuTab.route));

Creating a separate list of {title, url} records and explicitly listing all navigation links there is partially a duplication of the route config. But in practice that may be OK. Especially if the app has much more complex routing table than you want to render in the navigation menu.

Another way (not shown in the linked demo) would to be add extra properties into the route configuration. That means, for example, extending the Route type with custom metadata like title and canonicalUrl, and rendering a navigation menu based on that. There is a discussion and an example of how to add custom meta to routes: https://github.com/vaadin/vaadin-router/issues/444