Hilla Documentation

Hilla Router

Using Hilla Router.

Hilla Router is a small yet powerful client-side router JavaScript library. It uses a widely adopted express.js syntax for routers (users/:id) to map URLs to views. It has all the features of a modern router: async route resolution, animated transition, child routes, navigation guards, redirects, and more.

Hilla Router works with Web Components regardless of how they are created. It also offers a JavaScript API for regular HTML elements.

Hilla Router is distributed as the @vaadin/vaadin-router npm package. It is included in @vaadin/vaadin-core, and is automatically included in any Hilla application.

Using the Router

Add Hilla Router into the index.ts file by using the import statement. Then create and export a router instance by passing the outlet element in the index.html file:

<html>
  <body>
    <h1>My App</h1>
    <div id="outlet"></div>
  </body>
</html>
import { Router } from '@vaadin/router';
const outlet = document.querySelector('#outlet');
export const router = new Router(outlet);

Router configuration is done by using a set of routes that map URL paths to components.

Hilla Router goes through the routes until it encounters the first match. It then creates an element instance for the component specified by the route, and inserts this element in the router outlet, replacing any pre-existing elements.

router.setRoutes([
  {
    path: 'help',
    component: 'app-help',
    action: async () => { await import('./views/app-help-view'); }
  },
  {
    path: 'categories',
    component: 'app-categories',
    action: async () => { await import('./views/app-categories-view'); }
  }
]);

The router instance can be imported and used in the component’s file:

import { html, LitElement } from 'lit';
import { customElement, property } from 'lit/decorators.js';
import { router } from './index';

@customElement('app-help')
class AppHelpElement extends LitElement {
  @property({type: Object}) location = router.location;

  render() {
    return html`
      <p>Your location URL: ${this.location.getUrl()}</p>
      <nav>
        <a href="${router.urlForPath('/categories')}">Categories</a>
      </nav>
    `;
  }
}