1.0.0-alpha.1 • Published 7 years ago
myra-router v1.0.0-alpha.1
myra-router
A router for Myra framework
Installation
Install with NPM:
npm install myra-router --save
Usage
Start by importing the router module:
import * as router from 'myra-router'
Setting a base path
If your app resides at a non-root path, you will need to set the base path:
router.setBasePath('custompath')
Listening to route changes
To start listening to route changes you will need to:
- create an
Update
function to be used as callback for route changes. It will receive the state of the component and aRouteContext
:
const onRoute = (ctx: router.RouteContext) =>
evolve({ routeCtx: ctx })
- register a listener with the
router.addListener
function:
events.didMount = () => router.addListener(onRoute)
The RouteContext
The RouteContext
contains the following properties:
url: string
The current URL
params: Map<string>
The current query parameters
match: (route: string) => Result
A function to check if the current location matches a route.
matchAny: <T>(routes: PatternMap<T>, defaultValue: T) => T
a function to check if the current location matches any route. This function is suited for use within a view:
state =>
<div>
{state.routeCtx.matchAny({
'test1': <p>Route to '/test1'.</p>,
'test1/:param': (params: { param: string }) =>
<p>Route to '/test1/{params.param}'</p>
}, <nothing />)}
</div>
Updating the location
The routeTo
function pushes (or replaces) the history
state.
<button onclick={() => router.routeTo('path') }>
Push location to 'path'
</button>
<button onclick={() => router.routeTo('path2', { param: 'value' }, true) }>
Replace location with 'path2'
</button>
The goBack
and goForward
functions moves back and
forward in the history.
<button onclick={() => router.goBack() }>
Go back
</button>
<button onclick={() => router.goForward() }>
Go forward
</button>
Full example
import * as myra from 'myra'
import * as router from 'myra-router'
router.setBasePath('custom')
type State = {
routeCtx: router.RouteContext
}
const init = {} as State
export default myra.define(init, (evolve, events) => {
const onRoute = (ctx: router.RouteContext) =>
evolve({ routeCtx: ctx })
events.didMount = () => router.addListener(onRoute)
return state =>
<div>
{state.routeCtx.matchAny({
'test1': <p>Route to '/test1'.</p>,
'test1/:param': (params: { param: string }) =>
<p>Route to '/test1/{params.param}'</p>
}, <nothing />)}
{state.routeCtx.match('test1/:param').match ?
<p>Route '/test2/:param' matched.</p> : <nothing />}
<button onclick={() => router.routeTo('path') }>
Push location to 'path'
</button>
<button onclick={() => router.routeTo('path2', { param: 'value' }, true) }>
Replace location with 'path2'
</button>
<button onclick={() => router.goBack() }>
Go back
</button>
<button onclick={() => router.goForward() }>
Go forward
</button>
</div>
})
License
Copyright (c) 2016-2017 Jonathan Hedrén