npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@mpt/preact-router

v3.3.0

Published

This is meant to be an alternative for [preact-router](https://www.npmjs.com/package/preact-router) that covers more complex use cases.

Downloads

4

Readme

@mpt/preact-router

This is meant to be an alternative for preact-router that covers more complex use cases.

Note that this is not a drop in replacement for preact-router.

Features

  • history and hash based routing.
  • manual & custom route matching and formatting.
  • static & regular expression based routes.
  • nested router views.

Setup

npm i @mpt/preact-router

Note that this package can only be used as es modules for now.

import { HistoryRouter, StaticRoute, RouterView } from "@mpt/preact-router";

const routes = [
  [new StaticRoute("/"), () => <>Hello World!</>],
];

function Fallback() {
  return <>Not found :(</>;
}

render(
  <HistoryRouter>
    <RouterView routes={routes} fallback={Fallback} />
  </HistoryRouter>,
  document.body
);

The RouterView displays the first route that matches the current path. Otherwise it displays the fallback if provided.

Static Routes

Static routes can be used to match a static path and optionally all child paths.

import { StaticRoute } from "@mpt/preact-router";

new StaticRoute("/foo")
// Matches exactly "/foo"

new StaticRoute("/foo", true)
// Matches "/foo" and all child paths such as "/foo/bar/baz"

RegExp Routes

Regular expression routes can be used to parse dynamic parts from the path.

import { RegExpRoute } from "@mpt/preact-router";

function Page(props) {
  // Captured parts are passed to the routed component props:
  return <>Book id: {props.params[0]}</>;
}

const routes = [
  // Matches "/book/1234" and all children
  [new RegExpRoute(/^\/book\/(\d+)(?:\/|$)/), Page]
];

Manual Routing

Manual routing can be used to route a value based on the current path instead of rendering components.

import { routeValue } from "@mpt/preact-router";

const routes = [
  [new StaticRoute("/foo"), "foo"],
  [new StaticRoute("/bar"), "bar"],
];

function App() {
  // Note that the "routeValue" function relies on preact hooks to get the current path.
  const value = routeValue(routes);
  // Returns the first matched value or null if no route matches.

  return <>{value}</>;
}

To see what can be done with manual routing, you can take a look at https://mxjp.de/ .

Nested Routing

A router view provides information on the matched path to all of it's children, so that router views can be arbitrarily nested:

render(
  <HistoryRouter>
    <RouterView routes={[
      [new StaticRoute("/foo", true), () => <>
        <RouterView routes={[
          [new StaticRoute("/bar", true), () => {
            const route = useContext(routedContext);
            return <>{route.rest}</>;
          }]
        ]} />
      </>]
    ]} />
  </HistoryRouter>,
  document.body
);

When the location is "/foo/bar/baz", the above code renders "/baz".

Navigation

Both the HistoryRouter and HashRouter provide an api for programmatic navigation.

import { routerContext } from "@mpt/preact-router";

const someRoute = new StaticRoute("/foo");

function App() {
  // Returns an api for the currently used router:
  const router = useContext(routerContext);

  return <>
    <button onClick={() => {
      // Navigate to "/foo":
      router.push(someRoute.format());

      // Use the history api to replace the path with "/foo":
      router.replace(someRoute.format());
    }}>Foo</button>
  </>;
}

Note, that the replace function does the exact same as the push function if the HashRouter is used.

Path Normalization

The following conventions are used to normalize, combine and match route paths:

  • Normalized paths with at least one component always start with a "/".
  • A trailing slash indicates that the path represents a directory.
  • Paths must never contain empty components e.g. /foo//bar.

Troubleshooting

If routes are not matched as expected, the DebugView component can be used to display all available information in a specific context:

import { DebugView } from "@mpt/preact-router";

// location.pathname === "/foo/bar/baz?a=b"
render(
  <>
    <DebugView />
    <!-- no context -->

    <HistoryRouter>
      <DebugView />
      <!-- path="" rest="/foo/bar/baz" params="a=b" -->

      <RouterView routes={[
        [new StaticRoute("/foo", true), () => <>
          <DebugView />
          <!-- path="/foo" rest="/bar/baz" params="a=b" -->
        </>]
      ]} />
    </HistoryRouter>
  </>,
  document.body
)

Changelog

3.3.0

  • Add routeValueInContext function.

3.2.0

  • Add splitPath function.
  • Add deriveRoutedContext function.
  • Add RoutePathMatch interface without the params property that RouteMatch now extends.

3.1.0

  • Add onNavigate event to router interface.