DEV Community

Cover image for How to create Routing with Lit Library
Nelson Hernández
Nelson Hernández

Posted on

7 3

How to create Routing with Lit Library

In this example we will see how to add a router with vaadin router

Vaadin router

A small, powerful and framework-agnostic client-side router for Web Components

npm i @vaadin/router
Enter fullscreen mode Exit fullscreen mode
import { html, LitElement } from "lit";

export class Home extends LitElement {
  constructor() {
    super();
  }

  render() {
    return html`<div>
      <h1>Home</h1>
    </div>`;
  }
}
customElements.define("my-home", Home);
Enter fullscreen mode Exit fullscreen mode

main.js

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

function initRouter() {
  const router = new Router(document.querySelector("#app"));

  router.setRoutes([
    {
      path: "/",
      component: "my-home",
      action: () => import("./pages/Home")
    },
    {
      path: "/about",
      component: "my-about",
      action: () => import("./pages/About"),
    },
  ]);
}

window.addEventListener("load", () => initRouter());
Enter fullscreen mode Exit fullscreen mode
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/src/favicon.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + Lit App</title>
    <script type="module" src="src/main.js"></script>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay