Skip to content
Router for Kea
JavaScript
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src
.babelrc
.eslintrc
.gitignore
CHANGELOG.md
LICENSE.md
README.md
package.json
rollup.config.js
yarn.lock

README.md

NPM Version minified minified + gzipped Backers on Open Collective Sponsors on Open Collective

kea-router

Router plugin for kea. Works with kea 1.0.0-rc.8 and up.

Installation

kea-router depends on kea-listeners, so you must add both.

yarn add kea-router kea-listener

Add them to the plugins list when resetting the context:

import { routerPlugin } from 'kea-router'
import listenersPlugin from 'kea-listeners'

resetContext({
  plugins: [listenersPlugin, routerPlugin]
})

You may add extra options with routerPlugin(options), see the source for more :)

Sample usage

kea-router adds two fields to your logic: urlToAction and actionToUrl. See below for sample usage:

kea({
  // define the actions from below
  actions: () => ({ ... }),

  // define article = { id, ... }
  reducers: () => ({ ... }),

  actionToUrl: ({ actions, values }) => ({
    [actions.openList]: ({ id }) => `/articles`,
    [actions.openArticle]: ({ id }) => `/articles/${id}`,
    [actions.openComments]: () => `/articles/${values.article.id}/comments`,
    [actions.closeComments]: () => `/articles/${values.article.id}`
  }),

  urlToAction: ({ actions }) => ({
    '/articles': () => actions.openList(),
    '/articles/:id(/:extra)': ({ id, extra }) => {
      actions.openArticle(id)
      if (extra === 'comments') {
        actions.openComments()
      } else {
        actions.closeComments()
      }
    },
  })
})

To get or manipulate the route, import router and ask it for the following:

import { router } from 'kea-router'

kea({
  connect: {
    actions: [
      router, [
        'push',   // push(url)
        'replace' // replace(url),
        'locationChanged' // payload == { pathname, search, hash, method }
      ]
    ],
    values: [
      router, [
        'location' // { pathname, search, hash }
      ]
    ]
  }
})
You can’t perform that action at this time.