Last active
February 25, 2026 15:06
-
-
Save kevindurb/763ae5bdace325f9dc384c643f7d5d9d to your computer and use it in GitHub Desktop.
A basic lit js modern hash router thats so simple you dont need a library for it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export class HashRouter { | |
| #baseURL; | |
| #host; | |
| #routes; | |
| constructor(host, routes) { | |
| this.#baseURL = `${location.protocol}//${location.host}`; | |
| this.#host = host; | |
| this.#routes = routes.map(([p, render]) => [ | |
| new URLPattern(p, this.#baseURL), | |
| render, | |
| ]); | |
| this.#host.addController(this); | |
| } | |
| #onHashChange = () => this.#host.requestUpdate(); | |
| hostConnected() { | |
| window.addEventListener('hashchange', this.#onHashChange); | |
| } | |
| hostDisconnected() { | |
| window.removeEventListener('hashchange', this.#onHashChange); | |
| } | |
| render() { | |
| const path = window.location.hash.substring(1) || '/'; | |
| const url = new URL(path, this.#baseURL).href; | |
| for (const [pattern, render] of this.#routes) { | |
| const result = pattern.exec(url); | |
| if (result) return render(result.pathname.groups); | |
| } | |
| return null; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { LitElement, html } from 'lit'; | |
| import { HashRouter } from './HashRouter.js'; | |
| class Example extends LitElement { | |
| #router = new HashRouter(this, [ | |
| ['/', () => html`<h1>hello world</h1>`], | |
| ['/a', () => html`<h1>A</h1>`], | |
| ['/:id', (result) => html`<h1>${result.pathname.groups.id}</h1>`], | |
| ]); | |
| render() { | |
| return this.#router.render(); | |
| } | |
| } | |
| customElements.define('example', Example); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment