21 | )
22 | }
23 |
--------------------------------------------------------------------------------
/src/reducer.js:
--------------------------------------------------------------------------------
1 | /**
2 | * This action type will be dispatched when your history
3 | * receives a location change.
4 | */
5 | export const LOCATION_CHANGE = '@@router/LOCATION_CHANGE'
6 |
7 | const initialState = {
8 | locationBeforeTransitions: null
9 | }
10 |
11 | /**
12 | * This reducer will update the state with the most recent location history
13 | * has transitioned to. This may not be in sync with the router, particularly
14 | * if you have asynchronously-loaded routes, so reading from and relying on
15 | * this state is discouraged.
16 | */
17 | export function routerReducer(state = initialState, { type, payload } = {}) {
18 | if (type === LOCATION_CHANGE) {
19 | return { ...state, locationBeforeTransitions: payload }
20 | }
21 |
22 | return state
23 | }
24 |
--------------------------------------------------------------------------------
/examples/server/routes.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { Route, IndexRoute, Link } from 'react-router'
3 |
4 | const App = ({ children }) => (
5 |
)
22 |
23 | const routes = (
24 |
25 |
26 |
27 |
28 |
29 | )
30 |
31 | export default routes
32 |
--------------------------------------------------------------------------------
/examples/server/client.js:
--------------------------------------------------------------------------------
1 | import 'babel-polyfill'
2 |
3 | import React from 'react'
4 | import { render } from 'react-dom'
5 |
6 | import { Provider } from 'react-redux'
7 | import { Router, browserHistory } from 'react-router'
8 | import { syncHistoryWithStore } from 'react-router-redux'
9 |
10 | import { configureStore, DevTools } from './store'
11 | import routes from './routes'
12 |
13 | const store = configureStore(browserHistory, window.__initialState__)
14 | const history = syncHistoryWithStore(browserHistory, store)
15 |
16 | render(
17 |
18 |
19 | ,
20 | document.getElementById('root')
21 | )
22 |
23 | render(
24 |
25 |
26 | ,
27 | document.getElementById('devtools')
28 | )
29 |
--------------------------------------------------------------------------------
/test/middleware.spec.js:
--------------------------------------------------------------------------------
1 | import expect, { createSpy } from 'expect'
2 |
3 | import { push, replace } from '../src/actions'
4 | import routerMiddleware from '../src/middleware'
5 |
6 | describe('routerMiddleware', () => {
7 | let history, next, dispatch
8 |
9 | beforeEach(() => {
10 | history = {
11 | push: createSpy(),
12 | replace: createSpy()
13 | }
14 | next = createSpy()
15 |
16 | dispatch = routerMiddleware(history)()(next)
17 | })
18 |
19 |
20 | it('calls the appropriate history method', () => {
21 | dispatch(push('/foo'))
22 | expect(history.push).toHaveBeenCalled()
23 |
24 | dispatch(replace('/foo'))
25 | expect(history.replace).toHaveBeenCalled()
26 |
27 | expect(next).toNotHaveBeenCalled()
28 | })
29 |
30 | it('ignores other actions', () => {
31 | dispatch({ type: 'FOO' })
32 | expect(next).toHaveBeenCalled()
33 | })
34 | })
35 |
--------------------------------------------------------------------------------
/examples/basic/webpack.config.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable */
2 | const path = require('path');
3 |
4 | module.exports = {
5 | entry: './app.js',
6 | output: {
7 | path: path.join(__dirname, 'dist'),
8 | filename: 'bundle.js'
9 | },
10 | module: {
11 | loaders: [{
12 | test: /\.js$/,
13 | loader: 'babel',
14 | exclude: /node_modules/,
15 | include: __dirname
16 | }]
17 | }
18 | }
19 |
20 |
21 |
22 | // This will make the redux-simpler-router module resolve to the
23 | // latest src instead of using it from npm. Remove this if running
24 | // outside of the source.
25 | var src = path.join(__dirname, '..', '..', 'src')
26 | var fs = require('fs')
27 | if (fs.existsSync(src)) {
28 | // Use the latest src
29 | module.exports.resolve = { alias: { 'react-router-redux': src } }
30 | module.exports.module.loaders.push({
31 | test: /\.js$/,
32 | loaders: ['babel'],
33 | include: src
34 | });
35 | }
36 |
--------------------------------------------------------------------------------
/src/actions.js:
--------------------------------------------------------------------------------
1 | /**
2 | * This action type will be dispatched by the history actions below.
3 | * If you're writing a middleware to watch for navigation events, be sure to
4 | * look for actions of this type.
5 | */
6 | export const CALL_HISTORY_METHOD = '@@router/CALL_HISTORY_METHOD'
7 |
8 | function updateLocation(method) {
9 | return (...args) => ({
10 | type: CALL_HISTORY_METHOD,
11 | payload: { method, args }
12 | })
13 | }
14 |
15 | /**
16 | * These actions correspond to the history API.
17 | * The associated routerMiddleware will capture these events before they get to
18 | * your reducer and reissue them as the matching function on your history.
19 | */
20 | export const push = updateLocation('push')
21 | export const replace = updateLocation('replace')
22 | export const go = updateLocation('go')
23 | export const goBack = updateLocation('goBack')
24 | export const goForward = updateLocation('goForward')
25 |
26 | export const routerActions = { push, replace, go, goBack, goForward }
27 |
--------------------------------------------------------------------------------
/examples/server/webpack.config.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable */
2 | const path = require('path')
3 | const webpack = require('webpack')
4 |
5 | module.exports = {
6 | devtool: 'inline-source-map',
7 | entry: './client.js',
8 | output: {
9 | path: path.join(__dirname, 'dist'),
10 | filename: 'bundle.js',
11 | publicPath: '/__build__/'
12 | },
13 | module: {
14 | loaders: [{
15 | test: /\.js$/,
16 | loader: 'babel',
17 | exclude: /node_modules/,
18 | query: { plugins: [] }
19 | }]
20 | }
21 | }
22 |
23 |
24 | // This will make the redux-simpler-router module resolve to the
25 | // latest src instead of using it from npm. Remove this if running
26 | // outside of the source.
27 | var src = path.join(__dirname, '../../src')
28 | var fs = require('fs')
29 | if (fs.existsSync(src)) {
30 | // Use the latest src
31 | module.exports.resolve = { alias: { 'react-router-redux': src } }
32 | module.exports.module.loaders.push({
33 | test: /\.js$/,
34 | loaders: ['babel'],
35 | include: src
36 | });
37 | }
38 |
--------------------------------------------------------------------------------
/examples/basic/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "rrr-basic-example",
3 | "version": "0.0.0",
4 | "repository": "reactjs/react-router-redux",
5 | "license": "MIT",
6 | "dependencies": {
7 | "react": "^0.14.7",
8 | "react-dom": "^0.14.7",
9 | "react-redux": "^4.3.0",
10 | "react-router": "^2.0.0",
11 | "redux": "^3.2.1",
12 | "react-router-redux": "^4.0.0"
13 | },
14 | "devDependencies": {
15 | "babel-core": "^6.4.5",
16 | "babel-eslint": "^5.0.0-beta9",
17 | "babel-loader": "^6.2.2",
18 | "babel-preset-es2015": "^6.3.13",
19 | "babel-preset-react": "^6.3.13",
20 | "babel-preset-stage-1": "^6.3.13",
21 | "eslint": "^1.10.3",
22 | "eslint-config-rackt": "^1.1.1",
23 | "eslint-plugin-react": "^3.16.1",
24 | "redux-devtools": "^3.1.0",
25 | "redux-devtools-dock-monitor": "^1.0.1",
26 | "redux-devtools-log-monitor": "^1.0.4",
27 | "webpack": "^1.12.13",
28 | "webpack-dev-server": "^1.14.1"
29 | },
30 | "scripts": {
31 | "start": "webpack-dev-server --history-api-fallback --no-info --open"
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/examples/server/store.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 |
3 | import { createStore, combineReducers, compose, applyMiddleware } from 'redux'
4 | import { createDevTools } from 'redux-devtools'
5 | import LogMonitor from 'redux-devtools-log-monitor'
6 | import DockMonitor from 'redux-devtools-dock-monitor'
7 |
8 | import { routerReducer, routerMiddleware } from 'react-router-redux'
9 |
10 | export const DevTools = createDevTools(
11 |
12 |
13 |
14 | )
15 |
16 | export function configureStore(history, initialState) {
17 | const reducer = combineReducers({
18 | routing: routerReducer
19 | })
20 |
21 | let devTools = []
22 | if (typeof document !== 'undefined') {
23 | devTools = [ DevTools.instrument() ]
24 | }
25 |
26 | const store = createStore(
27 | reducer,
28 | initialState,
29 | compose(
30 | applyMiddleware(
31 | routerMiddleware(history)
32 | ),
33 | ...devTools
34 | )
35 | )
36 |
37 | return store
38 | }
39 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2015-present James Long
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy of
4 | this software and associated documentation files (the "Software"), to deal in
5 | the Software without restriction, including without limitation the rights to
6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7 | of the Software, and to permit persons to whom the Software is furnished to do
8 | so, subject to the following conditions:
9 |
10 | The above copyright notice and this permission notice shall be included in all
11 | copies or substantial portions of the Software.
12 |
13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 | SOFTWARE.
20 |
--------------------------------------------------------------------------------
/examples/server/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "rrr-server-example",
3 | "version": "0.0.0",
4 | "repository": "reactjs/react-router-redux",
5 | "license": "MIT",
6 | "dependencies": {
7 | "react": "^0.14.7",
8 | "react-dom": "^0.14.7",
9 | "react-redux": "^4.3.0",
10 | "react-router": "^2.0.0",
11 | "react-router-redux": "^4.0.0",
12 | "redux": "^3.2.1",
13 | "serialize-javascript": "^1.1.2"
14 | },
15 | "devDependencies": {
16 | "babel-cli": "^6.5.1",
17 | "babel-core": "^6.4.5",
18 | "babel-eslint": "^5.0.0-beta9",
19 | "babel-loader": "^6.2.2",
20 | "babel-plugin-module-alias": "^1.2.0",
21 | "babel-preset-es2015": "^6.3.13",
22 | "babel-preset-react": "^6.3.13",
23 | "babel-preset-stage-1": "^6.3.13",
24 | "babel-register": "^6.5.2",
25 | "eslint": "^1.10.3",
26 | "eslint-config-rackt": "^1.1.1",
27 | "eslint-plugin-react": "^3.16.1",
28 | "express": "^4.13.4",
29 | "redux-devtools": "^3.1.1",
30 | "redux-devtools-dock-monitor": "^1.0.1",
31 | "redux-devtools-log-monitor": "^1.0.4",
32 | "webpack": "^1.12.13",
33 | "webpack-dev-middleware": "^1.5.1"
34 | },
35 | "scripts": {
36 | "start": "babel-node server.js"
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/examples/basic/README.md:
--------------------------------------------------------------------------------
1 | react-router-redux basic example
2 | =================================
3 |
4 | This is a basic example that demonstrates rendering components based
5 | on URLs with `react-router` as well as connecting them to Redux state.
6 | It uses both `` elements as well as the `push` action creator
7 | provided by react-router-redux.
8 |
9 | This example also demonstrates integration with
10 | **[redux-devtools](https://github.com/gaearon/redux-devtools) ^3.0.0**
11 |
12 | **To run, follow these steps:**
13 |
14 | 1. Install dependencies with `npm install` in this directory (make sure it creates a local node_modules)
15 | 2. By default, it uses the local version from `src` of react-router-redux, so you need to run `npm install` from there first. If you want to use a version straight from npm, remove the lines in `webpack.config.js` at the bottom.
16 | 3. Start build with `npm start`
17 | 4. Open [http://localhost:8080/](http://localhost:8080/)
18 |
19 | -
20 |
21 | If you want to run the example from the npm published version of
22 | **react-router-redux**, remove the alias in `webpack.config`
23 | to the source from line 21.
24 |
25 | This example uses the latest version, switch to a specific tag to use a stable version:
26 |
27 | e.g. [react-router-redux tag 1.0.2](https://github.com/reactjs/react-router-redux/tree/1.0.2/examples/basic)
28 |
--------------------------------------------------------------------------------
/test/reducer.spec.js:
--------------------------------------------------------------------------------
1 | import expect from 'expect'
2 |
3 | import { LOCATION_CHANGE, routerReducer } from '../src/reducer'
4 |
5 | describe('routerReducer', () => {
6 | const state = {
7 | locationBeforeTransitions: {
8 | pathname: '/foo',
9 | action: 'POP'
10 | }
11 | }
12 |
13 | it('updates the path', () => {
14 | expect(routerReducer(state, {
15 | type: LOCATION_CHANGE,
16 | payload: {
17 | path: '/bar',
18 | action: 'PUSH'
19 | }
20 | })).toEqual({
21 | locationBeforeTransitions: {
22 | path: '/bar',
23 | action: 'PUSH'
24 | }
25 | })
26 | })
27 |
28 | it('works with initialState', () => {
29 | expect(routerReducer(undefined, {
30 | type: LOCATION_CHANGE,
31 | payload: {
32 | path: '/bar',
33 | action: 'PUSH'
34 | }
35 | })).toEqual({
36 | locationBeforeTransitions: {
37 | path: '/bar',
38 | action: 'PUSH'
39 | }
40 | })
41 | })
42 |
43 |
44 | it('respects replace', () => {
45 | expect(routerReducer(state, {
46 | type: LOCATION_CHANGE,
47 | payload: {
48 | path: '/bar',
49 | action: 'REPLACE'
50 | }
51 | })).toEqual({
52 | locationBeforeTransitions: {
53 | path: '/bar',
54 | action: 'REPLACE'
55 | }
56 | })
57 | })
58 | })
59 |
--------------------------------------------------------------------------------
/examples/basic/app.js:
--------------------------------------------------------------------------------
1 | import { createDevTools } from 'redux-devtools'
2 | import LogMonitor from 'redux-devtools-log-monitor'
3 | import DockMonitor from 'redux-devtools-dock-monitor'
4 |
5 | import React from 'react'
6 | import ReactDOM from 'react-dom'
7 | import { createStore, combineReducers } from 'redux'
8 | import { Provider } from 'react-redux'
9 | import { Router, Route, IndexRoute, browserHistory } from 'react-router'
10 | import { syncHistoryWithStore, routerReducer } from 'react-router-redux'
11 |
12 | import * as reducers from './reducers'
13 | import { App, Home, Foo, Bar } from './components'
14 |
15 | const reducer = combineReducers({
16 | ...reducers,
17 | routing: routerReducer
18 | })
19 |
20 | const DevTools = createDevTools(
21 |
22 |
23 |
24 | )
25 |
26 | const store = createStore(
27 | reducer,
28 | DevTools.instrument()
29 | )
30 | const history = syncHistoryWithStore(browserHistory, store)
31 |
32 | ReactDOM.render(
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 | ,
45 | document.getElementById('mount')
46 | )
47 |
--------------------------------------------------------------------------------
/karma.conf.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 |
3 | const path = require('path')
4 |
5 | module.exports = function (config) {
6 |
7 | let runCoverage = process.env.COVERAGE === 'true'
8 |
9 | let coverageLoaders = []
10 | let coverageReporters = []
11 |
12 | if (runCoverage) {
13 | coverageLoaders.push({
14 | test: /\.js$/,
15 | include: path.resolve('src/'),
16 | loader: 'isparta'
17 | }),
18 |
19 | coverageReporters.push('coverage')
20 | }
21 |
22 | config.set({
23 |
24 | browsers: [ 'Firefox' ],
25 | frameworks: [ 'mocha' ],
26 | reporters: [ 'mocha' ].concat(coverageReporters),
27 |
28 | files: [
29 | 'tests.webpack.js'
30 | ],
31 |
32 | preprocessors: {
33 | 'tests.webpack.js': [ 'webpack', 'sourcemap' ]
34 | },
35 |
36 | singleRun: true,
37 |
38 | webpack: {
39 | devtool: 'inline-source-map',
40 | module: {
41 | rules: [
42 | {
43 | test: /\.js$/,
44 | enforce: "pre",
45 | use: 'babel-loader',
46 | include: [
47 | path.resolve('src/'),
48 | path.resolve('test/')
49 | ]
50 |
51 | }
52 | ].concat(coverageLoaders)
53 | }
54 | },
55 |
56 | webpackServer: {
57 | noInfo: true
58 | },
59 |
60 | coverageReporter: {
61 | reporters: [
62 | { type: 'text' },
63 | { type: 'json', subdir: 'browser-coverage', file: 'coverage.json' }
64 | ]
65 | }
66 | })
67 | }
68 |
--------------------------------------------------------------------------------
/examples/server/server.js:
--------------------------------------------------------------------------------
1 | /*eslint-disable no-console */
2 | import express from 'express'
3 | import serialize from 'serialize-javascript'
4 |
5 | import webpack from 'webpack'
6 | import webpackDevMiddleware from 'webpack-dev-middleware'
7 | import webpackConfig from './webpack.config'
8 |
9 | import React from 'react'
10 | import { renderToString } from 'react-dom/server'
11 | import { Provider } from 'react-redux'
12 | import { createMemoryHistory, match, RouterContext } from 'react-router'
13 | import { syncHistoryWithStore } from '../../src'
14 |
15 | import { configureStore } from './store'
16 | import routes from './routes'
17 |
18 | const app = express()
19 |
20 | app.use(webpackDevMiddleware(webpack(webpackConfig), {
21 | publicPath: '/__build__/',
22 | stats: {
23 | colors: true
24 | }
25 | }))
26 |
27 | const HTML = ({ content, store }) => (
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 | )
37 |
38 | app.use(function (req, res) {
39 | const memoryHistory = createMemoryHistory(req.url)
40 | const store = configureStore(memoryHistory)
41 | const history = syncHistoryWithStore(memoryHistory, store)
42 |
43 | match({ history, routes, location: req.url }, (error, redirectLocation, renderProps) => {
44 | if (error) {
45 | res.status(500).send(error.message)
46 | } else if (redirectLocation) {
47 | res.redirect(302, redirectLocation.pathname + redirectLocation.search)
48 | } else if (renderProps) {
49 | const content = renderToString(
50 |
51 |
52 |
53 | )
54 |
55 | res.send('\n' + renderToString())
56 | }
57 | })
58 | })
59 |
60 | app.listen(8080, function () {
61 | console.log('Server listening on http://localhost:8080, Ctrl+C to stop')
62 | })
63 |
--------------------------------------------------------------------------------
/test/actions.spec.js:
--------------------------------------------------------------------------------
1 | import expect from 'expect'
2 |
3 | import {
4 | CALL_HISTORY_METHOD,
5 | push, replace, go, goBack, goForward
6 | } from '../src/actions'
7 |
8 | describe('routerActions', () => {
9 |
10 | describe('push', () => {
11 | it('creates actions', () => {
12 | expect(push('/foo')).toEqual({
13 | type: CALL_HISTORY_METHOD,
14 | payload: {
15 | method: 'push',
16 | args: [ '/foo' ]
17 | }
18 | })
19 |
20 | expect(push({ pathname: '/foo', state: { the: 'state' } })).toEqual({
21 | type: CALL_HISTORY_METHOD,
22 | payload: {
23 | method: 'push',
24 | args: [ {
25 | pathname: '/foo',
26 | state: { the: 'state' }
27 | } ]
28 | }
29 | })
30 |
31 | expect(push('/foo', 'baz', 123)).toEqual({
32 | type: CALL_HISTORY_METHOD,
33 | payload: {
34 | method: 'push',
35 | args: [ '/foo' , 'baz', 123 ]
36 | }
37 | })
38 | })
39 | })
40 |
41 | describe('replace', () => {
42 | it('creates actions', () => {
43 | expect(replace('/foo')).toEqual({
44 | type: CALL_HISTORY_METHOD,
45 | payload: {
46 | method: 'replace',
47 | args: [ '/foo' ]
48 | }
49 | })
50 |
51 | expect(replace({ pathname: '/foo', state: { the: 'state' } })).toEqual({
52 | type: CALL_HISTORY_METHOD,
53 | payload: {
54 | method: 'replace',
55 | args: [ {
56 | pathname: '/foo',
57 | state: { the: 'state' }
58 | } ]
59 | }
60 | })
61 | })
62 | })
63 |
64 | describe('go', () => {
65 | it('creates actions', () => {
66 | expect(go(1)).toEqual({
67 | type: CALL_HISTORY_METHOD,
68 | payload: {
69 | method: 'go',
70 | args: [ 1 ]
71 | }
72 | })
73 | })
74 | })
75 |
76 | describe('goBack', () => {
77 | it('creates actions', () => {
78 | expect(goBack()).toEqual({
79 | type: CALL_HISTORY_METHOD,
80 | payload: {
81 | method: 'goBack',
82 | args: []
83 | }
84 | })
85 | })
86 | })
87 |
88 | describe('goForward', () => {
89 | it('creates actions', () => {
90 | expect(goForward()).toEqual({
91 | type: CALL_HISTORY_METHOD,
92 | payload: {
93 | method: 'goForward',
94 | args: []
95 | }
96 | })
97 | })
98 | })
99 |
100 | })
101 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-router-redux",
3 | "version": "4.0.8",
4 | "description": "Ruthlessly simple bindings to keep react-router and redux in sync",
5 | "main": "lib/index",
6 | "files": [
7 | "*.md",
8 | "dist",
9 | "LICENSE",
10 | "lib",
11 | "src"
12 | ],
13 | "repository": "reactjs/react-router-redux",
14 | "authors": [
15 | "James Long",
16 | "Tim Dorr"
17 | ],
18 | "license": "MIT",
19 | "scripts": {
20 | "build": "npm run build:commonjs & npm run build:umd & npm run build:umd:min",
21 | "build:commonjs": "mkdir -p lib && babel ./src -d lib",
22 | "build:umd": "webpack dist/ReactRouterRedux.js",
23 | "build:umd:min": "NODE_ENV=production webpack dist/ReactRouterRedux.min.js",
24 | "lint": "eslint examples src test",
25 | "test": "npm run lint && npm run test:node && npm run test:browser",
26 | "test:node": "mocha --compilers js:babel-register --recursive ./test/*.spec.js",
27 | "test:browser": "karma start",
28 | "test:cov": "npm run test:cov:browser && npm run test:cov:node && npm run test:cov:report",
29 | "test:cov:node": "babel-node $(npm bin)/isparta cover $(npm bin)/_mocha report --dir ./coverage/node-coverage -- --recursive ./test/node",
30 | "test:cov:browser": "COVERAGE=true karma start",
31 | "test:cov:report": "$(npm bin)/istanbul report --dir ./coverage --include **/*coverage.json html text",
32 | "prepublish": "npm run build"
33 | },
34 | "tags": [
35 | "react",
36 | "redux"
37 | ],
38 | "keywords": [
39 | "react",
40 | "redux",
41 | "router"
42 | ],
43 | "devDependencies": {
44 | "babel-cli": "^6.1.2",
45 | "babel-core": "^6.7.4",
46 | "babel-eslint": "^7.1.1",
47 | "babel-loader": "^6.2.0",
48 | "babel-plugin-transform-es3-member-expression-literals": "^6.5.0",
49 | "babel-plugin-transform-es3-property-literals": "^6.5.0",
50 | "babel-polyfill": "^6.7.4",
51 | "babel-preset-es2015": "^6.3.13",
52 | "babel-preset-react": "^6.5.0",
53 | "babel-preset-stage-1": "^6.3.13",
54 | "babel-register": "^6.4.3",
55 | "eslint": "^3.15.0",
56 | "eslint-config-react-app": "^0.5.0",
57 | "eslint-plugin-flowtype": "^2.29.2",
58 | "eslint-plugin-import": "^2.2.0",
59 | "eslint-plugin-jsx-a11y": "^4.0.0",
60 | "eslint-plugin-react": "^6.8.0",
61 | "expect": "^1.13.0",
62 | "history": "^3.0.0",
63 | "isparta": "^4.0.0",
64 | "isparta-loader": "^2.0.0",
65 | "karma": "^1.4.1",
66 | "karma-coverage": "^1.1.1",
67 | "karma-firefox-launcher": "^1.0.0",
68 | "karma-mocha": "^1.3.0",
69 | "karma-mocha-reporter": "^2.2.2",
70 | "karma-sourcemap-loader": "^0.3.5",
71 | "karma-webpack": "^2.0.2",
72 | "mocha": "^3.2.0",
73 | "react": "^15.4.2",
74 | "react-dom": "^15.4.2",
75 | "react-redux": "^5.0.2",
76 | "react-router": "^3.0.0",
77 | "redux": "^3.0.4",
78 | "redux-devtools": "^3.0.0",
79 | "redux-devtools-dock-monitor": "^1.0.1",
80 | "redux-devtools-log-monitor": "^1.0.1",
81 | "webpack": "^2.2.1"
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/sync.js:
--------------------------------------------------------------------------------
1 | import { LOCATION_CHANGE } from './reducer'
2 |
3 | const defaultSelectLocationState = state => state.routing
4 |
5 | /**
6 | * This function synchronizes your history state with the Redux store.
7 | * Location changes flow from history to the store. An enhanced history is
8 | * returned with a listen method that responds to store updates for location.
9 | *
10 | * When this history is provided to the router, this means the location data
11 | * will flow like this:
12 | * history.push -> store.dispatch -> enhancedHistory.listen -> router
13 | * This ensures that when the store state changes due to a replay or other
14 | * event, the router will be updated appropriately and can transition to the
15 | * correct router state.
16 | */
17 | export default function syncHistoryWithStore(history, store, {
18 | selectLocationState = defaultSelectLocationState,
19 | adjustUrlOnReplay = true
20 | } = {}) {
21 | // Ensure that the reducer is mounted on the store and functioning properly.
22 | if (typeof selectLocationState(store.getState()) === 'undefined') {
23 | throw new Error(
24 | 'Expected the routing state to be available either as `state.routing` ' +
25 | 'or as the custom expression you can specify as `selectLocationState` ' +
26 | 'in the `syncHistoryWithStore()` options. ' +
27 | 'Ensure you have added the `routerReducer` to your store\'s ' +
28 | 'reducers via `combineReducers` or whatever method you use to isolate ' +
29 | 'your reducers.'
30 | )
31 | }
32 |
33 | let initialLocation
34 | let isTimeTraveling
35 | let unsubscribeFromStore
36 | let unsubscribeFromHistory
37 | let currentLocation
38 |
39 | // What does the store say about current location?
40 | const getLocationInStore = (useInitialIfEmpty) => {
41 | const locationState = selectLocationState(store.getState())
42 | return locationState.locationBeforeTransitions ||
43 | (useInitialIfEmpty ? initialLocation : undefined)
44 | }
45 |
46 | // Init initialLocation with potential location in store
47 | initialLocation = getLocationInStore()
48 |
49 | // If the store is replayed, update the URL in the browser to match.
50 | if (adjustUrlOnReplay) {
51 | const handleStoreChange = () => {
52 | const locationInStore = getLocationInStore(true)
53 | if (currentLocation === locationInStore || initialLocation === locationInStore) {
54 | return
55 | }
56 |
57 | // Update address bar to reflect store state
58 | isTimeTraveling = true
59 | currentLocation = locationInStore
60 | history.transitionTo({
61 | ...locationInStore,
62 | action: 'PUSH'
63 | })
64 | isTimeTraveling = false
65 | }
66 |
67 | unsubscribeFromStore = store.subscribe(handleStoreChange)
68 | handleStoreChange()
69 | }
70 |
71 | // Whenever location changes, dispatch an action to get it in the store
72 | const handleLocationChange = (location) => {
73 | // ... unless we just caused that location change
74 | if (isTimeTraveling) {
75 | return
76 | }
77 |
78 | // Remember where we are
79 | currentLocation = location
80 |
81 | // Are we being called for the first time?
82 | if (!initialLocation) {
83 | // Remember as a fallback in case state is reset
84 | initialLocation = location
85 |
86 | // Respect persisted location, if any
87 | if (getLocationInStore()) {
88 | return
89 | }
90 | }
91 |
92 | // Tell the store to update by dispatching an action
93 | store.dispatch({
94 | type: LOCATION_CHANGE,
95 | payload: location
96 | })
97 | }
98 | unsubscribeFromHistory = history.listen(handleLocationChange)
99 |
100 | // History 3.x doesn't call listen synchronously, so fire the initial location change ourselves
101 | if (history.getCurrentLocation) {
102 | handleLocationChange(history.getCurrentLocation())
103 | }
104 |
105 | // The enhanced history uses store as source of truth
106 | return {
107 | ...history,
108 | // The listeners are subscribed to the store instead of history
109 | listen(listener) {
110 | // Copy of last location.
111 | let lastPublishedLocation = getLocationInStore(true)
112 |
113 | // Keep track of whether we unsubscribed, as Redux store
114 | // only applies changes in subscriptions on next dispatch
115 | let unsubscribed = false
116 | const unsubscribeFromStore = store.subscribe(() => {
117 | const currentLocation = getLocationInStore(true)
118 | if (currentLocation === lastPublishedLocation) {
119 | return
120 | }
121 | lastPublishedLocation = currentLocation
122 | if (!unsubscribed) {
123 | listener(lastPublishedLocation)
124 | }
125 | })
126 |
127 | // History 2.x listeners expect a synchronous call. Make the first call to the
128 | // listener after subscribing to the store, in case the listener causes a
129 | // location change (e.g. when it redirects)
130 | if (!history.getCurrentLocation) {
131 | listener(lastPublishedLocation)
132 | }
133 |
134 | // Let user unsubscribe later
135 | return () => {
136 | unsubscribed = true
137 | unsubscribeFromStore()
138 | }
139 | },
140 |
141 | // It also provides a way to destroy internal listeners
142 | unsubscribe() {
143 | if (adjustUrlOnReplay) {
144 | unsubscribeFromStore()
145 | }
146 | unsubscribeFromHistory()
147 | }
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | ## [4.0.8](https://github.com/reactjs/react-router-redux/compare/v4.0.7...v4.0.8)
2 |
3 | - Don't run listeners synchronously with history 3 [`b2c2259`](https://github.com/reactjs/react-router-redux/commit/b2c2259c189cafad3e6e68eac7729e74f2bd56a9)
4 |
5 | ## [4.0.7](https://github.com/reactjs/react-router-redux/compare/v4.0.6...v4.0.7)
6 |
7 | - Support history 3 [#476](https://github.com/reactjs/react-router-redux/pull/476)
8 |
9 | ## [4.0.6](https://github.com/reactjs/react-router-redux/compare/v4.0.5...v4.0.6)
10 |
11 | - Makes sure the state in the store matches the state in history when using SSR [#445](https://github.com/reactjs/react-router-redux/pull/445)
12 |
13 | ## [4.0.5](https://github.com/reactjs/react-router-redux/compare/v4.0.4...v4.0.5)
14 |
15 | - Initialize currentLocation to initial location from the store. [#403](https://github.com/reactjs/react-router-redux/pull/403)
16 |
17 | ## [4.0.4](https://github.com/reactjs/react-router-redux/compare/v4.0.2...v4.0.4)
18 |
19 | - Added a UMD build. [#362](https://github.com/reactjs/react-router-redux/pull/362)
20 |
21 | ## [4.0.2](https://github.com/reactjs/react-router-redux/compare/v4.0.1...v4.0.2)
22 |
23 | - Calling routerReducer() with no args crashes. [#350](https://github.com/reactjs/react-router-redux/pull/350)
24 |
25 | ## [4.0.1](https://github.com/reactjs/react-router-redux/compare/v4.0.0...v4.0.1)
26 |
27 | - Fix IE8 compatbility. [#344](https://github.com/reactjs/react-router-redux/pull/344)
28 |
29 | ## [4.0.0](https://github.com/reactjs/react-router-redux/compare/3.0.0...v4.0.0)
30 |
31 | This is a big breaking release, but the last one for the foreseeable future. The scope of this library has changed, so please re-evaluate its usefulness to you. You may not need it and this is ok!
32 |
33 | #### Summary of Changes
34 |
35 | The provided action creators and middleware are now separate from the history<->state syncing function. For the vast majority of cases, using action creators to trigger navigation is obsoleted by React Router's [new history singletons](https://github.com/reactjs/react-router/blob/master/upgrade-guides/v2.0.0.md#history-singletons-provided) provided in 2.0. Building this functionality in by default and coupling it to our history syncing logic no longer makes sense.
36 |
37 | We now sync by enhancing the history instance to listen for navigation events and dispatch those into the store. The enhanced history has its `listen` method overridden to respond to store changes, rather than directly to navigation events. When this history is provided to ``, the router will listen to it and receive these store changes. This means if we time travel with the store, the router will receive those store changes and update based on the location in the store, instead of what the browser says. Normal navigation events (hitting your browser back/forward buttons, telling a history singleton to `push` a location) flow through the history's listener like normal, so all the usual stuff works A-OK.
38 |
39 | ## [3.0.0](https://github.com/reactjs/react-router-redux/compare/2.1.0...3.0.0)
40 |
41 | Technically, 2.1.0 broke semver. The appropriate @timdorr's have been flogged. So, we're bumping the major version to catch up.
42 |
43 | - Fixed Resets in Redux Dev Tools. [3ae8110f](https://github.com/reactjs/react-router-redux/commit/3ae8110f)
44 | - Ensure the initialState is set properly. [a00acfd4](https://github.com/reactjs/react-router-redux/commit/a00acfd4)
45 | - Support any number of args on action creators [524898b5](https://github.com/reactjs/react-router-redux/commit/524898b5)
46 |
47 | ## [2.1.0](https://github.com/reactjs/react-router-redux/compare/2.0.4...2.1.0)
48 |
49 | - `listenForReplays` has a `selectLocationState` selector. [#218](https://github.com/reactjs/react-router-redux/pull/218)
50 | - Provide unscoped action creators. [#225](https://github.com/reactjs/react-router-redux/pull/225)
51 | - Example updated to use fully ES2015 syntax.
52 |
53 | ## [2.0.4](https://github.com/reactjs/react-router-redux/compare/2.0.2...2.0.4)
54 |
55 | - Remove `history` module published within the tarball. [#133](https://github.com/reactjs/react-router-redux/issues/133)
56 | - Make actions conform to [Flux Standard Action](https://github.com/acdlite/flux-standard-action). [#208](https://github.com/reactjs/react-router-redux/pull/208)
57 |
58 | ## [2.0.2](https://github.com/reactjs/react-router-redux/compare/1.0.2...2.0.2)
59 |
60 | Versions 2.0.0 and 2.0.1 were test releases for the 2.* series. 2.0.2 is the first public release.
61 |
62 | **A whole new API, with many breaking changes:**
63 |
64 | * `syncReduxAndRouter` is gone. Instead, call `syncHistory` with just the `history` object, which returns a middleware that you need to apply. (#141)
65 | * If you use redux devtools, you need to call `middleware.listenForReplays(store)` on the middleware returned from `syncHistory`. Create the store first with the middleware, then call this function with the store.
66 | * Action creators are now contained in a single object called `routeActions`. `go`, `goBack`, and `goForward` action creators have been added.
67 | * `UPDATE_PATH` is now `UPDATE_LOCATION`.
68 | * The fully parsed [location object](https://github.com/reactjs/history/blob/master/docs/Location.md) is now stored in the state instead of a URL string. To access the path, use `state.routing.location.pathname` instead of `state.routing.path`.
69 |
70 | [View the new docs](https://github.com/reactjs/react-router-redux#api)
71 |
72 | ## [1.0.2](https://github.com/reactjs/react-router-redux/compare/1.0.1...1.0.2)
73 |
74 | * Only publish relevant files to npm
75 |
76 | ## [1.0.1](https://github.com/reactjs/react-router-redux/compare/1.0.0...1.0.1)
77 |
78 | * Solve problem with `basename` causing infinite redirects (#103)
79 | * Switched to ES6 imports/exports internally, but should not affect outside users
80 |
81 | ## [1.0.0](https://github.com/reactjs/react-router-redux/compare/0.0.10...1.0.0)
82 | > 2015-12-09
83 |
84 | This release changes quite a bit so you'll have to update your code.
85 |
86 | **Breaking Changes:**
87 |
88 | * The `updatePath` action creator has been removed in favor of `pushPath` and `replacePath`. Use `pushPath` to get the same behavior as before. (#38)
89 | * We have added support for routing state (#38)
90 | * Our actions are now [FSA compliant](https://github.com/acdlite/flux-standard-action). This means if you are listening for the `UPDATE_PATH` action in a reducer you should get properties off the `payload` property. (#63)
91 |
92 | Other fixes:
93 |
94 | * Redux DevTools should now work as expected (#73)
95 | * As we no longer depend on `window.location`, `` should now work (#62)
96 | * We've done lots of work on finding the right way to stop cycles, so hopefully we shouldn't have any unnecessary location or store updates (#50)
97 |
--------------------------------------------------------------------------------
/test/_createSyncTest.js:
--------------------------------------------------------------------------------
1 | import expect from 'expect'
2 |
3 | import React from 'react'
4 | import ReactDOM from 'react-dom'
5 | import { Router, Route, useRouterHistory } from 'react-router'
6 | import { Provider } from 'react-redux'
7 | import { createStore, combineReducers } from 'redux'
8 | import { ActionCreators, instrument } from 'redux-devtools'
9 |
10 | import syncHistoryWithStore from '../src/sync'
11 | import { routerReducer } from '../src/reducer'
12 |
13 | expect.extend({
14 | toContainLocation({
15 | pathname,
16 | search = '',
17 | hash = '',
18 | state = null,
19 | query,
20 | action = 'PUSH'
21 | }) {
22 | const { locationBeforeTransitions } = this.actual.getState().routing
23 | const location = locationBeforeTransitions
24 |
25 | expect(location.pathname).toEqual(pathname)
26 | expect(location.search).toEqual(search)
27 | expect(location.hash).toEqual(hash)
28 | expect(location.state).toEqual(state)
29 | expect(location.query).toEqual(query)
30 | expect(location.action).toEqual(action)
31 | }
32 | })
33 |
34 |
35 | function createSyncedHistoryAndStore(originalHistory) {
36 |
37 | const store = createStore(combineReducers({
38 | routing: routerReducer
39 | }))
40 | const history = syncHistoryWithStore(originalHistory, store)
41 |
42 | return { history, store }
43 | }
44 |
45 | const defaultReset = () => {}
46 |
47 | export default function createTests(createHistory, name, reset = defaultReset) {
48 | describe(name, () => {
49 |
50 | beforeEach(reset)
51 |
52 | describe('syncHistoryWithStore', () => {
53 | let history, store
54 |
55 | beforeEach(() => {
56 | let synced = createSyncedHistoryAndStore(createHistory())
57 | history = synced.history
58 | store = synced.store
59 | })
60 |
61 | afterEach(() => {
62 | history.unsubscribe()
63 | })
64 |
65 | it('syncs history -> redux', () => {
66 | expect(store).toContainLocation({
67 | pathname: '/',
68 | action: 'POP'
69 | })
70 |
71 | history.push('/foo')
72 | expect(store).toContainLocation({
73 | pathname: '/foo'
74 | })
75 |
76 | history.push({ state: { bar: 'baz' }, pathname: '/foo' })
77 | expect(store).toContainLocation({
78 | pathname: '/foo',
79 | state: { bar: 'baz' },
80 | action: 'PUSH'
81 | })
82 |
83 | history.replace('/bar')
84 | expect(store).toContainLocation({
85 | pathname: '/bar',
86 | action: 'REPLACE'
87 | })
88 |
89 | history.push('/bar')
90 | expect(store).toContainLocation({
91 | pathname: '/bar',
92 | action: 'REPLACE' // Converted by history.
93 | })
94 |
95 | history.push('/bar?query=1')
96 | expect(store).toContainLocation({
97 | pathname: '/bar',
98 | search: '?query=1'
99 | })
100 |
101 | history.push('/bar#baz')
102 | expect(store).toContainLocation({
103 | pathname: '/bar',
104 | hash: '#baz'
105 | })
106 |
107 | history.replace({
108 | pathname: '/bar',
109 | search: '?query=1',
110 | state: { bar: 'baz' }
111 | })
112 | expect(store).toContainLocation({
113 | pathname: '/bar',
114 | search: '?query=1',
115 | state: { bar: 'baz' },
116 | action: 'REPLACE'
117 | })
118 |
119 | history.replace({
120 | pathname: '/bar',
121 | search: '?query=1',
122 | hash: '#hash=2',
123 | state: { bar: 'baz' }
124 | })
125 | expect(store).toContainLocation({
126 | pathname: '/bar',
127 | search: '?query=1',
128 | hash: '#hash=2',
129 | state: { bar: 'baz' },
130 | action: 'REPLACE'
131 | })
132 | })
133 |
134 | it('provides an unsubscribe method to stop listening to history and store', () => {
135 | history.push('/foo')
136 | expect(store).toContainLocation({
137 | pathname: '/foo'
138 | })
139 |
140 | history.unsubscribe()
141 |
142 | history.push('/bar')
143 | expect(store).toContainLocation({
144 | pathname: '/foo'
145 | })
146 | })
147 |
148 | it('updates the router even if path is the same', () => {
149 | history.push('/')
150 |
151 | const updates = []
152 | const historyUnsubscribe = history.listen(location => {
153 | updates.push(location.pathname)
154 | })
155 |
156 | history.push('/foo')
157 | history.push('/foo')
158 | history.replace('/foo')
159 |
160 | expect(updates).toEqual([ '/foo', '/foo', '/foo' ])
161 |
162 | historyUnsubscribe()
163 | })
164 | })
165 |
166 | describe('Server', () => {
167 | it('handles inital load correctly', () => {
168 | // Server
169 | const { store: serverStore } = createSyncedHistoryAndStore(createHistory('/'))
170 | expect(serverStore).toContainLocation({
171 | pathname: '/',
172 | action: 'POP'
173 | })
174 |
175 | // Client
176 | let clientStore = createStore(combineReducers({
177 | routing: routerReducer
178 | }), serverStore.getState())
179 | let clientHistory = useRouterHistory(createHistory)()
180 |
181 | const historyListen = expect.createSpy()
182 | const historyUnsubscribe = clientHistory.listen(historyListen)
183 |
184 | syncHistoryWithStore(clientHistory, clientStore)
185 |
186 | // History v3: Listener should not be called during initialization
187 | expect(historyListen.calls.length).toBe(0)
188 |
189 | clientStore.dispatch({
190 | type: 'non-router'
191 | })
192 |
193 | // We expect that we still didn't get any call to history after a non-router action is dispatched
194 | expect(historyListen.calls.length).toBe(0)
195 |
196 | historyUnsubscribe()
197 | })
198 | })
199 |
200 | describe('Redux DevTools', () => {
201 | let originalHistory, history, store, devToolsStore
202 |
203 | beforeEach(() => {
204 | originalHistory = createHistory()
205 |
206 | // Set initial URL before syncing
207 | originalHistory.push('/foo')
208 |
209 | store = createStore(
210 | combineReducers({
211 | routing: routerReducer
212 | }),
213 | instrument()
214 | )
215 | devToolsStore = store.liftedStore
216 |
217 | history = syncHistoryWithStore(originalHistory, store)
218 | })
219 |
220 | afterEach(() => {
221 | history.unsubscribe()
222 | })
223 |
224 | it('resets to the initial url', () => {
225 | let currentPath
226 | const historyUnsubscribe = history.listen(location => {
227 | currentPath = location.pathname
228 | })
229 |
230 | history.push('/bar')
231 | devToolsStore.dispatch(ActionCreators.reset())
232 |
233 | expect(currentPath).toEqual('/foo')
234 |
235 | historyUnsubscribe()
236 | })
237 |
238 | it('handles toggle after history change', () => {
239 | let currentPath
240 | const historyUnsubscribe = history.listen(location => {
241 | currentPath = location.pathname
242 | })
243 |
244 | history.push('/foo2') // DevTools action #2
245 | history.push('/foo3') // DevTools action #3
246 |
247 | // When we toggle an action, the devtools will revert the action
248 | // and we therefore expect the history to update to the previous path
249 | devToolsStore.dispatch(ActionCreators.toggleAction(3))
250 | expect(currentPath).toEqual('/foo2')
251 |
252 | historyUnsubscribe()
253 | })
254 | })
255 |
256 | if (typeof(document) !== 'undefined') {
257 | describe('Redux Router component', () => {
258 | let store, history, rootElement
259 |
260 | beforeEach(() => {
261 | store = createStore(combineReducers({
262 | routing: routerReducer
263 | }))
264 |
265 | history = syncHistoryWithStore(useRouterHistory(createHistory)(), store)
266 |
267 | rootElement = document.createElement('div')
268 | document.body.appendChild(rootElement)
269 | })
270 |
271 | afterEach(() => {
272 | history.unsubscribe()
273 | rootElement.parentNode.removeChild(rootElement)
274 | })
275 |
276 | it('syncs history -> components', () => {
277 | history.push('/foo')
278 |
279 | ReactDOM.render(
280 |
281 |
282 | ({props.children})}>
283 | (at /foo)} />
284 | (at /bar)} />
285 |
286 |
287 | ,
288 | rootElement
289 | )
290 | expect(rootElement.textContent).toEqual('at /foo')
291 |
292 | history.push('/bar')
293 | expect(rootElement.textContent).toEqual('at /bar')
294 | })
295 |
296 | it('syncs history -> components when the initial route gets replaced', () => {
297 | history.push('/foo')
298 |
299 | ReactDOM.render(
300 |
301 |
302 | ({props.children})}>
303 | replace('/bar')} />
304 | (at /bar)} />
305 |
306 |
307 | ,
308 | rootElement
309 | )
310 | expect(rootElement.textContent).toEqual('at /bar')
311 | })
312 | })
313 | }
314 | })
315 | }
316 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Project Deprecated
2 |
3 | This project is no longer maintained. For your Redux <-> Router syncing needs with React Router 4+, please see one of these libraries instead:
4 |
5 | * [connected-react-router](https://github.com/supasate/connected-react-router)
6 |
7 | ---
8 |
9 | ⚠️ **This repo is for react-router-redux 4.x, which is only compatible with react-router 2.x and 3.x**
10 |
11 | # react-router-redux
12 |
13 | [](https://www.npmjs.com/package/react-router-redux) [](https://www.npmjs.com/package/react-router-redux) [](https://travis-ci.org/reactjs/react-router-redux)
14 |
15 | > **Keep your router in sync with application state** :sparkles:
16 |
17 | _Formerly known as redux-simple-router_
18 |
19 | You're a smart person. You use [Redux](https://github.com/reactjs/redux) to manage your application state. You use [React Router](https://github.com/reactjs/react-router) to do routing. All is good.
20 |
21 | But the two libraries don't coordinate. You want to do time travel with your application state, but React Router doesn't navigate between pages when you replay actions. It controls an important part of application state: the URL.
22 |
23 | This library helps you keep that bit of state in sync with your Redux store. We keep a copy of the current location hidden in state. When you rewind your application state with a tool like [Redux DevTools](https://github.com/gaearon/redux-devtools), that state change is propagated to React Router so it can adjust the component tree accordingly. You can jump around in state, rewinding, replaying, and resetting as much as you'd like, and this library will ensure the two stay in sync at all times.
24 |
25 | **This library is not _necessary_ for using Redux together with React Router. You can use the two together just fine without any additional libraries. It is useful if you care about recording, persisting, and replaying user actions, using time travel. If you don't care about these features, just [use Redux and React Router directly](http://stackoverflow.com/questions/36722584/how-to-sync-redux-state-and-url-hash-tag-params/36749963#36749963).**
26 |
27 | ## Installation
28 |
29 | ```
30 | npm install --save react-router-redux
31 | ```
32 |
33 | ## How It Works
34 |
35 | This library allows you to use React Router's APIs as they are documented. And, you can use redux like you normally would, with a single app state. The library simply enhances a history instance to allow it to synchronize any changes it receives into application state.
36 |
37 | [history](https://github.com/reactjs/history) + `store` ([redux](https://github.com/reactjs/redux)) → [**react-router-redux**](https://github.com/reactjs/react-router-redux) → enhanced [history](https://github.com/reactjs/history) → [react-router](https://github.com/reactjs/react-router)
38 |
39 | ## Tutorial
40 |
41 | Let's take a look at a simple example.
42 |
43 | ```js
44 | import React from 'react'
45 | import ReactDOM from 'react-dom'
46 | import { createStore, combineReducers } from 'redux'
47 | import { Provider } from 'react-redux'
48 | import { Router, Route, browserHistory } from 'react-router'
49 | import { syncHistoryWithStore, routerReducer } from 'react-router-redux'
50 |
51 | import reducers from '/reducers'
52 |
53 | // Add the reducer to your store on the `routing` key
54 | const store = createStore(
55 | combineReducers({
56 | ...reducers,
57 | routing: routerReducer
58 | })
59 | )
60 |
61 | // Create an enhanced history that syncs navigation events with the store
62 | const history = syncHistoryWithStore(browserHistory, store)
63 |
64 | ReactDOM.render(
65 |
66 | { /* Tell the Router to use our enhanced history */ }
67 |
68 |
69 |
70 |
71 |
72 |
73 | ,
74 | document.getElementById('mount')
75 | )
76 | ```
77 |
78 | Now any time you navigate, which can come from pressing browser buttons or navigating in your application code, the enhanced history will first pass the new location through the Redux store and then on to React Router to update the component tree. If you time travel, it will also pass the new state to React Router to update the component tree again.
79 |
80 | #### How do I watch for navigation events, such as for analytics?
81 |
82 | Simply listen to the enhanced history via `history.listen`. This takes in a function that will receive a `location` any time the store updates. This includes any time travel activity performed on the store.
83 |
84 | ```js
85 | const history = syncHistoryWithStore(browserHistory, store)
86 |
87 | history.listen(location => analyticsService.track(location.pathname))
88 | ```
89 |
90 | For other kinds of events in your system, you can use middleware on your Redux store like normal to watch any action that is dispatched to the store.
91 |
92 | #### What if I use Immutable.js or another state wrapper with my Redux store?
93 |
94 | When using a wrapper for your store's state, such as Immutable.js, you will need to change two things from the standard setup:
95 |
96 | 1. By default, the library expects to find the history state at `state.routing`. If your wrapper prevents accessing properties directly, or you want to put the routing state elsewhere, pass a selector function to access the historystate via the `selectLocationState` option on `syncHistoryWithStore`.
97 | 2. Provide your own reducer function that will receive actions of type `LOCATION_CHANGE` and return the payload merged into the `locationBeforeTransitions` property of the routing state. For example, `state.set("routing", {locationBeforeTransitions: action.payload})`.
98 |
99 | These two hooks will allow you to store the state that this library uses in whatever format or wrapper you would like.
100 |
101 | #### How do I access router state in a container component?
102 |
103 | React Router [provides route information via a route component's props](https://github.com/ReactTraining/react-router/blob/v3/docs/Introduction.md#getting-url-parameters). This makes it easy to access them from a container component. When using [react-redux](https://github.com/reactjs/react-redux) to `connect()` your components to state, you can access the router's props from the [2nd argument of `mapStateToProps`](https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options):
104 |
105 | ```js
106 | function mapStateToProps(state, ownProps) {
107 | return {
108 | id: ownProps.params.id,
109 | filter: ownProps.location.query.filter
110 | };
111 | }
112 | ```
113 |
114 | You should not read the location state directly from the Redux store. This is because React Router operates asynchronously (to handle things such as dynamically-loaded components) and your component tree may not yet be updated in sync with your Redux state. You should rely on the props passed by React Router, as they are only updated after it has processed all asynchronous code.
115 |
116 | #### What if I want to issue navigation events via Redux actions?
117 |
118 | React Router provides singleton versions of history (`browserHistory` and `hashHistory`) that you can import and use from anywhere in your application. However, if you prefer Redux style actions, the library also provides a set of action creators and a middleware to capture them and redirect them to your history instance.
119 |
120 | ```js
121 | import { createStore, combineReducers, applyMiddleware } from 'redux';
122 | import { routerMiddleware, push } from 'react-router-redux'
123 |
124 | // Apply the middleware to the store
125 | const middleware = routerMiddleware(browserHistory)
126 | const store = createStore(
127 | reducers,
128 | applyMiddleware(middleware)
129 | )
130 |
131 | // Dispatch from anywhere like normal.
132 | store.dispatch(push('/foo'))
133 | ```
134 |
135 | ## Examples
136 |
137 | - [examples/basic](/examples/basic) - basic reference implementation
138 |
139 | Examples from the community:
140 |
141 | * [react-redux-styled-hot-universal](https://github.com/krasevych/react-redux-styled-hot-universal) (SSR, Universal Webpack, Redux, React-router, Webpack 2, Babel, Styled Components and more...)
142 | * [shakacode/react-webpack-rails-tutorial](https://github.com/shakacode/react-webpack-rails-tutorial) - react-router-redux including **Server Rendering** using [React on Rails](https://github.com/shakacode/react_on_rails/), live at [www.reactrails.com](http://www.reactrails.com/).
143 | * [davezuko/react-redux-starter-kit](https://github.com/davezuko/react-redux-starter-kit) - popular redux starter kit
144 | * **tip**: migrating from react-router-redux `^3.0.0`? use [this commit](https://github.com/davezuko/react-redux-starter-kit/commit/0df26907) as a reference
145 | * [svrcekmichal/universal-react](https://github.com/svrcekmichal/universal-react) - Universal react app with async actions provided by [svrcekmichal/reasync](https://github.com/svrcekmichal/reasync) package
146 | * [steveniseki/react-router-redux-example](https://github.com/StevenIseki/react-router-redux-example) - minimal react-router-redux example includes css modules and universal rendering
147 | * [choonkending/react-webpack-node](https://github.com/choonkending/react-webpack-node) - Full-stack universal Redux App
148 | * [kuy/treemap-with-router](https://github.com/kuy/treemap-with-router) - An example for react-router-redux with d3's treemap.
149 |
150 | → _Have an example to add? Send us a PR!_ ←
151 |
152 | ## API
153 |
154 | #### `routerReducer()`
155 |
156 | **You must add this reducer to your store for syncing to work.**
157 |
158 | A reducer function that stores location updates from `history`. If you use `combineReducers`, it should be nested under the `routing` key.
159 |
160 | #### `history = syncHistoryWithStore(history, store, [options])`
161 |
162 | Creates an enhanced history from the provided history. This history changes `history.listen` to pass all location updates through the provided store first. This ensures if the store is updated either from a navigation event or from a time travel action, such as a replay, the listeners of the enhanced history will stay in sync.
163 |
164 | **You must provide the enhanced history to your `` component.** This ensures your routes stay in sync with your location and your store at the same time.
165 |
166 | The `options` object takes in the following optional keys:
167 |
168 | - `selectLocationState` - (default `state => state.routing`) A selector function to obtain the history state from your store. Useful when not using the provided `routerReducer` to store history state. Allows you to use wrappers, such as Immutable.js.
169 | - `adjustUrlOnReplay` - (default `true`) When `false`, the URL will not be kept in sync during time travel. This is useful when using `persistState` from Redux DevTools and not wanting to maintain the URL state when restoring state.
170 |
171 | #### `push(location)`, `replace(location)`, `go(number)`, `goBack()`, `goForward()`
172 |
173 | **You must install `routerMiddleware` for these action creators to work.**
174 |
175 | Action creators that correspond with the [history methods of the same name](https://github.com/ReactTraining/history/blob/v3/docs/GettingStarted.md#navigation). For reference they are defined as follows:
176 |
177 | - `push` - Pushes a new location to history, becoming the current location.
178 | - `replace` - Replaces the current location in history.
179 | - `go` - Moves backwards or forwards a relative number of locations in history.
180 | - `goForward` - Moves forward one location. Equivalent to `go(1)`
181 | - `goBack` - Moves backwards one location. Equivalent to `go(-1)`
182 |
183 | Both `push` and `replace` take in a [location descriptor](https://github.com/ReactTraining/history/blob/v3/docs/Location.md), which can be an object describing the URL or a plain string URL.
184 |
185 | These action creators are also available in one single object as `routerActions`, which can be used as a convenience when using Redux's `bindActionCreators()`.
186 |
187 | #### `routerMiddleware(history)`
188 |
189 | A middleware you can apply to your Redux `store` to capture dispatched actions created by the action creators. It will redirect those actions to the provided `history` instance.
190 |
191 | #### `LOCATION_CHANGE`
192 |
193 | An action type that you can listen for in your reducers to be notified of route updates. Fires *after* any changes to history.
194 |
--------------------------------------------------------------------------------