Simple routing for your redux application.
The main purpose of this router is to mirror your browser history to the redux store and help you easily declare routes.
We also provide React bindings!
Install redux-unity-router
package from npm:
npm i --save redux-unity-router
Before proceeding to the next step, we suggest you create a file containing your routes:
/* routes.js */
export default {
id: 'Main',
pattern: '/application/',
data: {
pageTitle: 'My simple application'
},
routes: [
{
id: 'News',
pattern: '/news/',
data: {
pageTitle: 'My news'
},
routes: [
{
id: 'Item',
pattern: ':id'
}
]
},
{
id: 'Contacts',
pattern: '/contacts/'
}
]
};
You can learn more about setting up routes
and their structure in the API section.
Then require those routes
and set up your store
like this:
/* store.js */
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
// Previously defined routes
import routes from './routes.js';
import { createRouter, History } from 'redux-unity-router';
// Create history
const history = History.createBrowserHistory();
// Create router instance
const router = createRouter({ history, routes });
// Add router middleware to your list of middlewares
const middleware = [ router.middleware ];
// Enhance your store by using router's enhancer
const toEnhance = [
router.enhancer,
applyMiddleware(...middleware)
];
// Put it all together
const enhancer = compose(...toEnhance);
const reducers = combineReducers({
router: router.reducer
});
const initialState = {}
const store = createStore(reducers, initialState, enhancer);
export default store;
Now you've got yourself a simple routing system!
After navigating to /news/1?edit=true#title
you can expect your store's state to contain 'router'
entry similar to:
{
"pathname": "/news",
"search": "?edit=true",
"hash": "#title",
"key": "gmj9fs",
"query": {"edit": "true"},
"state": {},
"path": "/news/1?edit=true",
"route": {
"pattern": {"path": "/news/:id"},
"id": "Item",
"idPath": "News:Item",
"params": {"id": "1"},
"data": {"pageTitle": "My news"}
}
}
You can manage your layout by using <RouterProvider>
, <Fragment>
and <Link>
React-components.
They should help keep your application simple and maintainable.
import { createRouter } from 'redux-unity-router'
Router factory, that returns an instance of the router object, containing: middleware, enhancer and reducer.
History object created by abstraction over browser's History API.
An array of routes. If any of the routes can be matched to the same pattern, the route that has been declared first in routes
array will take precedence.
Default: false
If you use immutable store, set this to true
.
Default: 'router'
Store's key, that will contain router
's data.
An object containing route's definition.
Redux-Unity-Router uses path-to-regexp for route-matching. There's also a handy tool to test your patterns.
Although you can declare patterns in the form of string
s, that becomes problematic, when you want to match a route with query parameters, that may appear in arbitrary order. For this situation you may want to declare a pattern in a form of a plain object
:
Same as you'd declare a pattern in a form of a string.
Plain query object.
Default: equals pattern
if typeof pattern === 'string'
or pattern.path
if typeof pattern === 'object'
Unique Id of the route.
It is recommended that you define route's id, so you can easily navigate to it with <Link>
component.
Any arbitrary data you want reflected in the redux store, when the route is matched.
Any sub-routes a route may have. All the patterns and data of these sub-routes will be merged with their parent's . Sub-routes always take precedence over their parents in the matching process.
const routes = [
{
id: 'User',
pattern: '/user/:id',
data: {
pageTitle: 'User Profile'
}
routes: [
{
id: 'UserEdit',
data: {
pageTitle: 'Edit User Profile'
},
pattern: {
query: {
edit: 'true'
}
}
},
{
id: 'UserLogout',
data: {
message: 'goodbye'
},
pattern: {
path: 'logout'
}
}
]
}
]
// This will produce 3 patterns:
// { path: '/user/:id', query: { edit: 'true' }, data: { pageTitle: 'User Profile' } }
// { path: '/user/:id/logout', data: { pageTitle: 'Edit User Profile' } }
// { path: '/user/:id', data: { pageTitle: 'User Profile', message: ''goodbye' } }
import { actions } from 'redux-unity-router'
or
import actions from 'redux-unity-router/actions'
Actually, these are action-creators (functions, that produce plain action objects). You can use them if you want to programmatically navigate to any part of your application. Most of them correspond to standard methods of browser's History API (except for goToRoute
and locationChange
).
Navigate to new url/path.
payload
of typestring
will be interpreted as path or url.payload
of typeobject
should contain one the following properties:
e.g. '/news'
e.g. '?edit=true'
e.g. '#title'
Default: false
This extra option allows you to change current location url without propagating changes to the Redux store.
Navigate to new url/path, replacing current history entry.
Same as for push
action.
Go back or forward in history stack.
e.g. -1
Equivalent to go(-1)
.
Equivalent to go(1)
.
Navigate to the predefined route.
Valid route ID.
If our route contains parameters, you should provide them here.
Plain query object.
Hash for the resulting url.
If you've defined a route like this:
{
id: 'Preferences',
pattern: '/prefs/:action'
}
and you want to navigate to /prefs/edit?edit=true#title
, you should dispatch an action like this:
store.dispatch(actions.goToRoute({
id: 'Preferences',
params: { action: 'edit' },
query: { edit: true },
hash: 'title'
}));
You most likely will never use this one, as it is used by Redux-Unity-Router internally to produce an entirely new router state.
Check your store for this one!
import { actionTypes } from 'redux-unity-router'
or
import actionTypes from 'redux-unity-router/actionTypes'
Internally Redux-Unity-Router dispatches actions with following action-types
-
@@REDUX_UNITY_ROUTER/**LOCATION_CHANGED**
-
@@REDUX_UNITY_ROUTER/**PUSH**
-
@@REDUX_UNITY_ROUTER/**REPLACE**
-
@@REDUX_UNITY_ROUTER/**GO**
-
@@REDUX_UNITY_ROUTER/**GO_BACK**
-
@@REDUX_UNITY_ROUTER/**GO_FORWARD**
-
@@REDUX_UNITY_ROUTER/**GO_TO_ROUTE**
Keep in mind, that if you want to handle actions with these action-types in your reducers, all actions except for @@REDUX_UNITY_ROUTER/LOCATION_CHANGED will be swallowed by Redux-Unity-Router's middleware.
Although you can easily manage application's layout based on the router's redux store data, we do provide some handy react components for you to use:
An array of routes. We advice you use the same array for both createRouter
and <RouterProvider>
.
Default: false
If you use immutable store, set this to true
.
Default: 'router'
Store's key, that will contain router
's data. Use the same one you've used in createRouter
setting up your store.
Supports all default <a>
properties.
string
type will be interpreted as path or url (external urls are supported as well)object
type can be interpreted 2 ways: if it has propertyid
, it will be interpreted asroute
(see actions.goToRoute), otherwise it will be considered as a standard location object (see actions.push).
Default: 'link'
className
for the generated link.
Default: 'link__active'
className
that will be added to the link if it matches current route.
Default: null
Target attribute.
Default: false
Dictates whether and how activeClass
should be added to the link.
false
- no current route matching at all. This is the default behavior.'exact'
- link will receive itsactiveClass
only if itspathname
,query
andhash
match current route's.'partial'
- link will receive itsactiveClass
when current route'spathname
begins with thepathname
supplied to link.'{RegExp}'
- if you supply a regular expression, current route's entirepath
will be tested against it.
Default: undefined
Optional onClick
callback, that will be fired before <Link>
dispatches its navigation action. If this callback returns a {Promise}
, <Link>
's navigation action will be fired, when the returned {Promise}
resolves.
// Navigates to /application
<Link to="/application" activeMatch="exact">Main page</Link>
// Navigates to /application/news?id=1#comment-box
<Link to={{ pathname: '/application/news', query: { id: '1' }, hash: 'comment-box' }}>News</Link>
// if route is defined like { id: 'Settings', pattern: '/user/:userId' } navigates to /user/1?edit=true#title
<Link to={{ id: 'Settings', params: { userId: '1' }, query: { edit: true }, hash: '#title' }}></Link>
Displays react components and other <Fragment>
s based on current route.
Route's ID that you want a <Fragment>
displayed on.
Redirect to path
, url
or route
, when id
is the last in the chain of nested <Fragment>'
s ids.
See <Link>
's to
prop.
You can pass react component to be used as a direct child of the <Fragment>
.
<Fragment id="Main">
Main component for my application.
<Fragment id="News">
Component with my news list.
</Fragment>
<Fragment id="Gallery" component={Gallery} /> // imported <Gallery> react component
<Fragment id="Contacts">
<Fragment id="Map" component={Map} /> // imported <Map> react component
</Fragment>
<Fragment id="Redirect" redirect={{ id: 'Redirected' }} />
<Fragment id="Redirected">
You have been redirected here.
</Fragment>
</Fragment>
We provide a basic example of working React app that you can dig into. Just clone this repo and run:
npm run build:examples
- Provide conventional commit messages by using
npm run commit
instead ofgit commit
. - Core contributors: use GitHub's Rebase and merge as a default way of merging PRs.
MIT © AuRu