Skip to main content

Router

What is a router?

In web development, a router is a component or functionality that helps handle the routing or navigation within a web application. It's responsible for determining what content or component should be displayed on the user's screen based on the current URL or user's interaction.

Vaadin Router

In the StarterKit plugin we use Vaadin Router.

Vaadin Router automatically listens to navigation events and asynchronously renders a matching web component into the given DOM node, referred to as the router outlet.

The routes config file maps URL paths to the corresponding web components. Vaadin Router goes through the routes until it finds the first match, creates an instance of the route component, and inserts it into the router outlet (replacing any pre-existing outlet content).

More details and demos of Vaadin Router can be found here:

Vaadin Router Demo

Implementation

/src/application/application.ts

The router is imported by the main application component:

import { router } from "./routes";

The target element of the router is rendered by the main application component and has ID outlet:

<div id="content-wrapper">
<div id="outlet"></div>
</div>

/src/application/routes.ts

The Vaadin Router dependency is imported:

import { Router } from "@vaadin/router";

Any web component referenced within the router configuration must also be imported:

import "../pages/dashboard/dashboard";
import "../pages/detail/detail-page";
import "../pages/dummy/dummy-page";

All routes are then defined in the routes array:

const routes = [
{
path: "(.*)?/",
animate: true,
component: "uwc-starterkit-dashboard"
},
{
path: "(.*)?/index(.*).html",
animate: true,
component: "uwc-starterkit-dashboard"
},
{
path: "(.*)?/detail/:id",
animate: true,
component: "uwc-starterkit-detail"
}
]

The router is created using the router target element with ID outlet and the routes array defined:

export const router = new Router(document.getElementById("outlet"));
requestAnimationFrame(() => {
setTimeout(() => {
router.setRoutes(routes);
}, 1);
});