literaljs-router
v1.0.0
Published
A tiny client-side router for LiteralJS v8+. Returns VNodes, supports named parameters, and works with the App class API.
Maintainers
Readme
LiteralJS Router v1.0.0
A tiny client-side router for LiteralJS v8+.
- Returns VNodes — works directly with LiteralJS
h()and the v8 renderer - Named parameters —
/users/:idextracts{ id: '123' } - Programmatic navigation —
navigate('/about')with pushState - App class API — triggers re-render via CustomEvent, no
set()callback needed - Zero extra dependencies — only needs
literaljsas a peer dep - ~600 bytes gzipped
Install
npm install literaljs-routerUsage
/** @jsx h */
import { h, component, App } from 'literaljs';
import { Router, navigate } from 'literaljs-router';
// Define page components
const Home = component({
name: 'Home',
render() {
return (
<div>
<h1>Welcome Home</h1>
<button events={{ click: () => navigate('/docs') }}>
Go to Docs
</button>
</div>
);
}
});
const Docs = component({
name: 'Docs',
render() {
return <div><h1>Documentation</h1></div>;
}
});
// Define routes
const routes = [
{ path: '/', render: () => h(Home) },
{ path: '/docs', render: () => h(Docs) },
{ path: '/404', render: () => h('div', {}, 'Not Found') }
];
// Root component uses Router
const App = component({
name: 'App',
render() {
return (
<div>
<nav>...</nav>
<Router routes={routes} />
</div>
);
}
});
new App(App, {}).mount('root');Named Parameters
const routes = [
{ path: '/users/:id', render: ({ params }) => h(UserPage, { userId: params.id }) },
];
// navigate('/users/42') → params = { id: '42' }API
Router({ routes, key? })
The main router component. Place it in your root component's render method.
routes— Array of{ path: string, render: (ctx) => VNode }objectskey— Store key for current path (default:'location')
The render function receives { params, path } as its argument.
navigate(path)
Programmatically navigate to a path. Uses history.pushState and dispatches a popstate event.
import { navigate } from 'literaljs-router';
navigate('/about');getParams()
Parse query string parameters from the current URL.
import { getParams } from 'literaljs-router';
// On /search?q=hello&page=2
const params = getParams(); // { q: 'hello', page: '2' }getPathParams(pattern, path)
Extract named parameters from a matched route pattern.
Changes from v0.x
- Returns VNodes (
h()calls) instead of plain objects - Named route parameters (
:id,:slug, etc.) navigate()for programmatic navigation- CustomEvent-based re-render trigger (compatible with App class)
- No mutable
set()callback — works with v8.0.4 App API - Smaller footprint
License
MIT
