• This repository has been archived on 27/Oct/2018
  • Stars
    star
    7,824
  • Rank 4,600 (Top 0.1 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Ruthlessly simple bindings to keep react-router and redux in sync

Project Deprecated

This project is no longer maintained. For your Redux <-> Router syncing needs with React Router 4+, please see one of these libraries instead:


⚠️ This repo is for react-router-redux 4.x, which is only compatible with react-router 2.x and 3.x

react-router-redux

npm version npm downloads build status

Keep your router in sync with application state

Formerly known as redux-simple-router

You're a smart person. You use Redux to manage your application state. You use React Router to do routing. All is good.

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.

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, 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.

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.

Installation

npm install --save react-router-redux

How It Works

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.

history + store (redux) → react-router-redux → enhanced historyreact-router

Tutorial

Let's take a look at a simple example.

import React from 'react'
import ReactDOM from 'react-dom'
import { createStore, combineReducers } from 'redux'
import { Provider } from 'react-redux'
import { Router, Route, browserHistory } from 'react-router'
import { syncHistoryWithStore, routerReducer } from 'react-router-redux'

import reducers from '<project-path>/reducers'

// Add the reducer to your store on the `routing` key
const store = createStore(
  combineReducers({
    ...reducers,
    routing: routerReducer
  })
)

// Create an enhanced history that syncs navigation events with the store
const history = syncHistoryWithStore(browserHistory, store)

ReactDOM.render(
  <Provider store={store}>
    { /* Tell the Router to use our enhanced history */ }
    <Router history={history}>
      <Route path="/" component={App}>
        <Route path="foo" component={Foo}/>
        <Route path="bar" component={Bar}/>
      </Route>
    </Router>
  </Provider>,
  document.getElementById('mount')
)

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.

How do I watch for navigation events, such as for analytics?

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.

const history = syncHistoryWithStore(browserHistory, store)

history.listen(location => analyticsService.track(location.pathname))

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.

What if I use Immutable.js or another state wrapper with my Redux store?

When using a wrapper for your store's state, such as Immutable.js, you will need to change two things from the standard setup:

  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.
  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}).

These two hooks will allow you to store the state that this library uses in whatever format or wrapper you would like.

How do I access router state in a container component?

React Router provides route information via a route component's props. This makes it easy to access them from a container component. When using react-redux to connect() your components to state, you can access the router's props from the 2nd argument of mapStateToProps:

function mapStateToProps(state, ownProps) {
  return {
    id: ownProps.params.id,
    filter: ownProps.location.query.filter
  };
}

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.

What if I want to issue navigation events via Redux actions?

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.

import { createStore, combineReducers, applyMiddleware } from 'redux';
import { routerMiddleware, push } from 'react-router-redux'

// Apply the middleware to the store
const middleware = routerMiddleware(browserHistory)
const store = createStore(
  reducers,
  applyMiddleware(middleware)
)

// Dispatch from anywhere like normal.
store.dispatch(push('/foo'))

Examples

Examples from the community:

Have an example to add? Send us a PR!

API

routerReducer()

You must add this reducer to your store for syncing to work.

A reducer function that stores location updates from history. If you use combineReducers, it should be nested under the routing key.

history = syncHistoryWithStore(history, store, [options])

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.

You must provide the enhanced history to your <Router> component. This ensures your routes stay in sync with your location and your store at the same time.

The options object takes in the following optional keys:

  • 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.
  • 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.

push(location), replace(location), go(number), goBack(), goForward()

You must install routerMiddleware for these action creators to work.

Action creators that correspond with the history methods of the same name. For reference they are defined as follows:

  • push - Pushes a new location to history, becoming the current location.
  • replace - Replaces the current location in history.
  • go - Moves backwards or forwards a relative number of locations in history.
  • goForward - Moves forward one location. Equivalent to go(1)
  • goBack - Moves backwards one location. Equivalent to go(-1)

Both push and replace take in a location descriptor, which can be an object describing the URL or a plain string URL.

These action creators are also available in one single object as routerActions, which can be used as a convenience when using Redux's bindActionCreators().

routerMiddleware(history)

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.

LOCATION_CHANGE

An action type that you can listen for in your reducers to be notified of route updates. Fires after any changes to history.

More Repositories

1

react.dev

The React documentation website
TypeScript
10,714
star
2

react-transition-group

An easy way to perform animations when a React component enters or leaves the DOM
JavaScript
10,074
star
3

react-modal

Accessible modal dialog component for React
JavaScript
7,314
star
4

react-rails

Integrate React.js with Rails views and controllers, the asset pipeline, or webpacker.
JavaScript
6,725
star
5

react-router-tutorial

JavaScript
5,532
star
6

rfcs

RFCs for changes to React
5,377
star
7

react-basic

A description of the conceptual model of React without implementation burden.
4,163
star
8

server-components-demo

Demo app of React Server Components.
JavaScript
4,140
star
9

react-codemod

React codemod scripts
JavaScript
4,053
star
10

react-docgen

A CLI and library to extract information from React component files for documentation generation purposes.
TypeScript
3,557
star
11

react-tutorial

Code from the React tutorial.
JavaScript
3,294
star
12

react-tabs

An accessible and easy tab component for ReactJS.
JavaScript
3,048
star
13

react-chartjs

common react charting components using chart.js
JavaScript
2,930
star
14

react-future

Specs & docs for potential future and experimental React APIs and JavaScript syntax.
JavaScript
2,824
star
15

express-react-views

This is an Express view engine which renders React components on server. It renders static markup and *does not* support mounting those views on the client.
JavaScript
2,732
star
16

react-a11y

Identifies accessibility issues in your React.js elements
JavaScript
2,332
star
17

React.NET

.NET library for JSX compilation and server-side rendering of React components
C#
2,269
star
18

react-autocomplete

WAI-ARIA compliant React autocomplete (combobox) component
JavaScript
2,161
star
19

react-art

React Bridge to the ART Drawing Library
JavaScript
1,987
star
20

react-php-v8js

PHP library that renders React components on the server
PHP
1,325
star
21

react-magic

Automatically AJAXify plain HTML with the power of React. It's magic!
JavaScript
939
star
22

core-notes

Weekly meeting notes from the React core team
899
star
23

zh-hans.react.dev

React documentation website in Simplified Chinese
TypeScript
876
star
24

ru.react.dev

React documentation website in Russian / Официальная русская версия сайта React
TypeScript
673
star
25

ko.react.dev

React documentation website in Korean
TypeScript
660
star
26

pt-br.react.dev

🇧🇷 React documentation website in Portuguese (Brazil)
TypeScript
465
star
27

react-lifecycles-compat

Backwards compatibility polyfill for React class components
JavaScript
459
star
28

react-gradual-upgrade-demo

Demonstration of how to gradually upgrade an app to a new version of React
JavaScript
420
star
29

react-timer-mixin

TimerMixin provides timer functions for executing code in the future that are safely cleaned up when the component unmounts
JavaScript
309
star
30

id.react.dev

(Work in progress) React documentation website in Indonesian
TypeScript
305
star
31

es.react.dev

React documentation website in Spanish / Documentación del sitio web de React en Español
TypeScript
272
star
32

translations.react.dev

Nexus of resources and tools for translating the React docs.
JavaScript
254
star
33

ja.react.dev

React documentation website in Japanese
TypeScript
243
star
34

react-static-container

Renders static content efficiently by allowing React to short-circuit the reconciliation process.
JavaScript
222
star
35

fa.react.dev

(Work in progress) React documentation website in Persian
TypeScript
182
star
36

tr.react.dev

React documentation website in Turkish
TypeScript
161
star
37

uk.react.dev

🇺🇦 React documentation website in Ukrainian / Офіційна українська версія сайту React
TypeScript
130
star
38

ar.react.dev

React documentation website in Arabic 📘⚛️ — وثائق React باللغة العربية
TypeScript
126
star
39

hi.react.dev

(Work in progress) React documentation website in Hindi
TypeScript
110
star
40

zh-hant.react.dev

(Work in progress) React documentation website in Traditional Chinese
TypeScript
105
star
41

bn.react.dev

(Work in progress) React documentation website in Bengali
TypeScript
98
star
42

fr.react.dev

Version française du site de documentation officiel de React
TypeScript
91
star
43

vi.react.dev

(Work in progress) React documentation website in Vietnamese
TypeScript
84
star
44

react-bower

[DISCONTINUED] Bower package for React
JavaScript
69
star
45

legacy.reactjs.org

An archived copy of the legacy React documentation website
JavaScript
60
star
46

bn.reactjs.org

(Work in progress) React documentation website in Bengali
JavaScript
54
star
47

ta.reactjs.org

(Work in progress) React documentation website in Tamil
JavaScript
52
star
48

pl.react.dev

React documentation website in Polish
TypeScript
49
star
49

az.react.dev

🇦🇿 React documentation website in Azerbaijani
TypeScript
43
star
50

rackt-codemod

Codemod scripts for Rackt libraries
JavaScript
40
star
51

th.reactjs.org

(Work in progress) React documentation website in Thai
JavaScript
40
star
52

mn.react.dev

(Work in progress) React documentation website in Mongolian
TypeScript
37
star
53

uz.reactjs.org

(Work in progress) React documentation website in Uzbek
TypeScript
36
star
54

de.react.dev

(Work in progress) React documentation website in German
TypeScript
33
star
55

si.reactjs.org

(Work in progress) React documentation website in Sinhala
JavaScript
32
star
56

ml.react.dev

(Work in progress) React documentation website in Malayalam
TypeScript
31
star
57

it.react.dev

(Work in progress) React documentation website in Italian
TypeScript
30
star
58

ur.reactjs.org

(⚠️ Beta Docs Translation only) React documentation website in Urdu. Check details in https://github.com/reactjs/ur.reactjs.org/issues/1#issuecomment-949791355
TypeScript
29
star
59

he.react.dev

(Work in progress) React documentation website in Hebrew
TypeScript
28
star
60

ku.reactjs.org

(Work in progress) React documentation website in Kurdish
JavaScript
28
star
61

hu.react.dev

Hungarian 🇭🇺 React ⚛ documentation 📚 / React magyar dokumentációja
TypeScript
26
star
62

be.react.dev

(Work in progress) React documentation website in Belarusian
TypeScript
26
star
63

ml.reactjs.org

(Work in progress) React documentation website in Malayalam
JavaScript
25
star
64

ur.react.dev

(Work in progress) React documentation website in Urdu
TypeScript
25
star
65

el.reactjs.org

(Work in progress) React documentation website in Greek
JavaScript
25
star
66

gu.react.dev

(Work in progress) React documentation website in Gujarati
TypeScript
24
star
67

pt-PT.reactjs.org

(Work in progress) React documentation website in Portuguese (Portugal) 🇵🇹
JavaScript
23
star
68

ne.reactjs.org

(Work in progress) React documentation website in Nepali
JavaScript
23
star
69

gu.reactjs.org

(Work in progress) React documentation website in Gujarati
JavaScript
22
star
70

te.reactjs.org

(Work in progress) React documentation website in Telugu
JavaScript
22
star
71

hy.reactjs.org

(Work in progress) React documentation website in Armenian - https://hy.reactjs.org
JavaScript
21
star
72

km.reactjs.org

(Work in progress) React documentation website in Central Khmer
JavaScript
20
star
73

bg.reactjs.org

(Work in progress) React documentation website in Bulgarian
JavaScript
16
star
74

ro.reactjs.org

(Work in progress) React documentation website in Romanian
JavaScript
16
star
75

si.react.dev

(Work in progress) React documentation website in Sinhala
TypeScript
14
star
76

kn.reactjs.org

(Work in progress) React documentation website in Kannada
JavaScript
13
star
77

tl.reactjs.org

(Work in progress) React documentation website in Tagalog
TypeScript
13
star
78

ka.reactjs.org

(Work in progress) React documentation website in Georgian
JavaScript
11
star
79

sv.reactjs.org

(Work in progress) React documentation website in Swedish
JavaScript
9
star
80

nl.reactjs.org

(Work in progress) React documentation website in Dutch
JavaScript
8
star
81

ca.reactjs.org

(Work in progress) React documentation website in Catalan
JavaScript
7
star
82

te.react.dev

(Work in progress) React documentation website in Telugu
TypeScript
7
star
83

sw.react.dev

(Work in progress) React documentation website in Swahili
TypeScript
7
star
84

lt.reactjs.org

(Work in progress) React documentation website in Lithuanian
JavaScript
6
star
85

ta.react.dev

(Work in progress) React documentation website in Tamil
TypeScript
6
star
86

ht.reactjs.org

(Work in progress) React documentation website in Haitian Creole
JavaScript
5
star
87

sr.reactjs.org

(Work in progress) React documentation website in Serbian
TypeScript
5
star
88

is.react.dev

(Work in progress) React documentation website in Icelandic
TypeScript
4
star
89

cs.react.dev

(Work in progress) React documentation website in Czech
TypeScript
4
star
90

kk.react.dev

🇰🇿 React documentation website in Kazakh / React сайтының ресми қазақша нұсқасы
TypeScript
3
star
91

sr.react.dev

(Work in progress) React documentation website in Serbian
TypeScript
3
star
92

sq.reactjs.org

(Work in progress) React documentation website in Albanian
TypeScript
3
star
93

reactjs.github.io

HTML
2
star
94

lo.react.dev

(Work in progress) React documentation website in Lao
TypeScript
2
star
95

fi.react.dev

(Work in progress) React documentation website in Finnish
TypeScript
2
star
96

my.reactjs.org

(Work in progress) React documentation website in Burmese
JavaScript
2
star
97

sw.reactjs.org

(Work in progress) React documentation website in Swahili
JavaScript
2
star
98

mk.react.dev

(Work in progress) React documentation website in Macedonian
TypeScript
1
star
99

tg.reactjs.org

(Work in progress) React documentation website in Tajik
TypeScript
1
star