redux-route

0.0.3 • Public • Published

Redux Route

How would you implement routing if the address bar was just a regular input element?

Build Status

By default redux-route uses the addressbar module which makes the window's location behave like any other input field.

On top of that it uses the awesome url-pattern library to perform the matching.

With this combination it's very simple to keep all the routing information inside the redux state which should be you application's single source of truth:

import { createRouter, routeReducer } from 'redux-route';
 
const router = createRouter({
  home: '/',
  items: '/items/(:id)'
});
 
const rootReducer = combineReducers({
  route: routeReducer,
  // other reducers ...
});
 
// Dispatch actions when the URL changes:
router.connectToStore(store);

The redux state will now provide routing information under the key you chose. If /items/23 was requested state.route would be:

{
  path: '/items/23',
  params: { id: 23 },
  name: 'items'
}

Component Selection

Use state.route.name to select which top-level component you want to display. Instead of a switch statement you can also use the selectComponent helper:

import { selectComponent } from 'redux-route';
 
const mapStateToProps = selectComponent({
  home: (params, path) => <Home />,
  NO_MATCH: () => <Error />
});
 
connect(mapStateToProps)(Component);

Adapters

Redux-route provides several adapters to obtain or modify the actual location:

  • hash: Uses location.hash and hashchange events and also works in legacy browsers.
  • addressbar: Uses the addressbar module.
  • auto: Uses addressbar if supported and falls back to hash. This is the default.
  • fixed: A static URL for server-side routing. Requires no DOM.

The adapter interface is very simple so you can provide your own implementation to match your needs.

Credits

Thanks to Arnaud Rinquin for writing redux-reroute. This project started as a fork of his awesome work and the example app is still pretty much the same.

Thanks to Christian Alfoni for making addressbar such a generic and standalone module.

Thanks to Callum Jefferies for redux-routing which is another awesome routing library that with its universal routing support inspired me to go with the adapters approach.

Thanks to Maximilian Krüger for writing url-pattern which made it really easy to turn all the ideas into a lightweight router.

License

MIT

Package Sidebar

Install

npm i redux-route

Weekly Downloads

4

Version

0.0.3

License

MIT

Last publish

Collaborators

  • fgnass