router icon indicating copy to clipboard operation
router copied to clipboard

Styled router links

Open vlukashov opened this issue 7 years ago • 2 comments

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 active property should automatically be updated when the current URL changes
  • to support Polymer integration, changes in the active property should trigger active-changed events (non-bubbling)
  • if not configured otherwise, the active property should be set if the current path matches the href property
  • if an active-path string property is set, the active property should be set if the current path matches the path specified in the active-path property
  • if an active-path property is set, the default is prefix-matching. It can be changed to exact matching by adding an exact boolean property
  • there is a demo showing both the basic href matching and the path matching

The common DoD applies.

vlukashov avatar Apr 25 '18 11:04 vlukashov

+1 for the feature!

aress31 avatar Jul 02 '20 16:07 aress31

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:

  • add more properties into the existing router config and use it to render the menu
  • create a separate (simpler) config for the navigation links, and render the menu based on that

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

vlukashov avatar Jul 02 '20 20:07 vlukashov