Install dependencies
preact-iso is the actively developed package by the Preact team - since preact-router has been deprecated.
npm install preact-iso
Create App Component
Create your main App Component and make sure to wrap everything inside a LocationProvider, as this enables navigation and related hooks. Optionally, add ErrorBoundary with onError handler to catch potential runtime errors.
import { ErrorBoundary, LocationProvider, Route, Router } from 'preact-iso';
export const App = () => (
<LocationProvider>
<ErrorBoundary onError={e => console.log(e)}></ErrorBoundary>
</LocationProvider>
);
Create Pages
Create simple Functional Components to be used as Pages - for example, Home as our HomePage and NotFound for unmatched routes.
const Home = () => <h2>Home</h2>;
const NotFound = () => <h2>Page Not Found!</h2>;
Add routes
Add the pages as routes inside Router by assigning them to the component prop.
The Home route uses the path ”/” and will be rendered initially.
The default route will render the NotFound Page when no other route matches.
export const App = () => (
<LocationProvider>
<ErrorBoundary onError={e => console.log(e)}>
<Router>
+ <Route path="/" component={Home} />
+ <Route default component={NotFound} />
</Router>
</ErrorBoundary>
</LocationProvider>
);
Add Navigation Links
preact-iso provides a Link component that enables client-side navigation.
Add the following Links to test navigation between routes.
export const App = () => (
<LocationProvider>
<ErrorBoundary onError={e => console.log(e)}>
+ <Link href="/">Home</Link>
+ <Link href="/about">About</Link>
<Router>
<Route path="/" component={Home} />
<Route default component={NotFound} />
</Router>
</ErrorBoundary>
</LocationProvider>
);
Test it
Run the app and check the Links.
As expected, /about is not defined as a Route. So clicking on it should redirect to our NotFound Component.
Clicking on /home redirects to home as expected.
Location
In addition to routing, preact-iso provides hooks like useLocation, which let you inspect the current pathname, search query, hash, or navigation state.
const location = useLocation();
// extract search query
const query = new URLSearchParams(location.search);
const name = query.get('name');
Live Example
See it live in action on Stackblitz