/router

Utilities for routing client-side pages with Hyperapp.

Primary LanguageJavaScriptMIT LicenseMIT

@hyperapp/router

Travis CI Codecov npm Slack

@hyperapp/router provides utilities for routing client-side pages with Hyperapp using the History API.

Try it Online

import { router, Link } from "@hyperapp/router"

app({
  view: [
    [
      "/",
      (state, actions) =>
        <Link to="/test" go={actions.router.go}>
          Test
        </Link>
    ],
    [
      "/test",
      (state, actions) =>
        <Link to="/" go={actions.router.go}>
          Back
        </Link>
    ]
  ],
  mixins: [router()]
})

Installation

Download the minified library from a CDN.

<script src="https://unpkg.com/@hyperapp/router"></script>

Then import from router.

const { router, Link } = router

Or install with npm / Yarn.

npm i @hyperapp/router

Then bundle and use as you would any other module.

import { router, Link } from "@hyperapp/router"

Mixin

Use the router as any other mixin. Then compose your view as an array of routes.

app({
  view: [
    ["/", state => <h1>Hi.</h1>]
    ["*", state => <h1>404</h1>],
  ],
  mixins: [router()]
})

Routes

A route is a tuple that consists of a path and a view.

[string, View]

Routes are matched in the following three scenarios:

If location.pathname matches the path of a supplied route, we'll render its view.

Paths

/, /foo

Match if location.pathname is /, /foo, etc.

/:key

Match location.pathname using [A-Za-z0-9]+ and save the matched path to state.router.params.

*

Match anything. Declaration order dictates matching precedence. If you are using *, declare it last.

state.router.match

The matched path.

string

state.router.params

The matched path params.

{
  [key]: string
}
path location.pathname state.router.params
/:foo /hyper { foo: "hyper" }

actions.router.go

Update location.pathname with the supplied path.

actions.router.go(path)

events.route

Use route to make a network request, parse location.search, etc. This event is fired when a new route is matched.

route(State, Actions, RouteInfo): RouteInfo

RouteInfo

{
  match: string,
  params: any
}

Link

Use Link to create hyperlinks that map to a route.

<Link to="/" go={actions.router.go}>Back Home</Link>

to

A route path.

go

A function that will be called with the supplied path when the hyperlink is clicked.

License

@hyperapp/router is MIT licensed. See LICENSE.