📡 Router | Preact

A tiny router for Preact apps. It connects your app with the address bar. That's it.
Features
- Tiny footprint (less than 1KB gzipped!)
- No dependencies (BYO Preact/HTM)
- Comprehensive test suite (100% code coverage)
- Suitable for production use
- MIT license
- Browser-native ESM friendly (designed specifically to require zero build tools to run)
Installing
npm install --save router-preact
Yarn users, you know what to do instead.
Usage
The following examples are written in JSX format, for brevity.
Example: Basic Usage
import { Link, Route } from 'router-preact';
const App = () => <>
<Route path="/">
<Link to="/next">Next page</Link>
</Route>
<Route path="/next">
<Link to="/">First page</Link>
</Route>
</>;
Example: Parameterized Routes
import { Link, Route, pattern } from 'router-preact';
const App = () => <>
<Route path="/">
<Link to="/pages/1">Go to page 1</Link>
</Route>
<Route path={pattern`/pages/${'pageNumber'}`} render={({ params: { pageNumber } }) => <>
<p>Thank you for visiting page {pageNumber}.</p>
<Link to={`/pages/${pageNumber + 1}`}>Go to next page</Link>
</>}/>
</>;
Example: Redirection
import { Redirect, Route } from 'router-preact';
const App = () => <>
<Route path="/">
<Redirect to="/pages/1"/>
</Route>
</>;
Advanced Example: Intercepting the Router
If you really want to, you can swap out the router implementation by
using the Router
context provided by this package. For example, if
you want to test a component that involves routing.
import { Router } from 'router-preact';
const myRouter = {
match(path) {
},
navigate(path) {
},
onNavigate: (callback) => () => {
},
path() {
},
query() {
}
};
const App = () => <Router.Provider value={myRouter}>
...
</>;