andyrj / router

Actions and events for routing client-side pages with HyperApp.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

@hyperapp/router

Travis CI Codecov npm Slack

@hyperapp/router provides actions and events for routing client-side pages with HyperApp using the History API.

Installation

Using npm:

npm i @hyperapp/router

Then setup a build pipeline and import it.

import { Router } from "@hyperapp/router"

Using a CDN:

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

Then access the router in the global scope as Router.

Usage

Register the router as a mixin. Then compose your view as an array of route/view pairs.

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

When the page loads or the browser fires a popstate event, the first route that matches location.pathname will be rendered.

Routes are matched in the order in which they are declared. To use the wildcard * correctly, it must be declared last.

route location.pathname
/ /
/:foo Match [A-Za-z0-9]+. See params.
* Match anything.

To navigate to a different route use actions.router.go.

Example

Try it online

app({
  view: [
    [
      "/",
      (state, actions) =>
        <div>
          <h1>Home</h1>
          <a href="#about">About</a>
        </div>
    ],
    [
      "/:route",
      (state, actions) =>
        <div>
          <h1>About</h1>
          <a href="#home">Home</a>
        </div>
    ]
  ],
  mixins: [Router]
})

API

state

params

Type: { foo: string, ... }

The matched route params.

route location.pathname state.router.params
/:foo /hyper { foo: "hyper" }

match

Type: string

The matched route.

actions

go

Type: (path)

  • path: string

Update location.pathname.

events

route

Type: (state, actions, data, emit) | Array<route>

Fired when a route is matched.

License

@hyperapp/router is MIT licensed. See LICENSE.

About

Actions and events for routing client-side pages with HyperApp.

License:MIT License


Languages

Language:JavaScript 100.0%