What is connected-react-router?
connected-react-router is a library that integrates React Router with Redux, allowing you to keep your router state in sync with your Redux store. This can be particularly useful for applications that require complex state management and routing logic.
What are connected-react-router's main functionalities?
Synchronize Router State with Redux
This code demonstrates how to set up a Redux store that is synchronized with React Router. It uses `createBrowserHistory` to create a history object, `routerMiddleware` to intercept navigation actions, and `connectRouter` to create a reducer that keeps the router state in sync with the Redux store. The `ConnectedRouter` component is then used to render the router, ensuring that the router state is managed by Redux.
import { createBrowserHistory } from 'history';
import { applyMiddleware, createStore } from 'redux';
import { routerMiddleware } from 'connected-react-router';
import { connectRouter } from 'connected-react-router';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router';
import { Route, Switch } from 'react-router';
import React from 'react';
import ReactDOM from 'react-dom';
const history = createBrowserHistory();
const store = createStore(
connectRouter(history)(rootReducer),
applyMiddleware(routerMiddleware(history))
);
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</Switch>
</ConnectedRouter>
</Provider>,
document.getElementById('root')
);
Dispatch Navigation Actions
This code demonstrates how to dispatch navigation actions using the `push` function from `connected-react-router`. This allows you to programmatically navigate to different routes within your application by dispatching actions to the Redux store.
import { push } from 'connected-react-router';
// Dispatch a navigation action
store.dispatch(push('/about'));
Access Router State in Redux
This code demonstrates how to access the router state from within a React component using the `useSelector` hook from `react-redux`. This allows you to read the current location and other router state properties directly from the Redux store.
import { useSelector } from 'react-redux';
const MyComponent = () => {
const location = useSelector(state => state.router.location);
return <div>Current Path: {location.pathname}</div>;
};
Other packages similar to connected-react-router
react-router-redux
react-router-redux is another library that aims to keep React Router and Redux in sync. However, it is no longer actively maintained and has been deprecated in favor of connected-react-router. It provides similar functionality but lacks the ongoing support and updates.
redux-first-router
redux-first-router is a library that takes a different approach by making routing a first-class citizen in Redux. It allows you to define routes as part of your Redux actions and reducers, providing a more integrated approach to routing and state management. It offers more control over routing logic but can be more complex to set up compared to connected-react-router.
Connected React Router
A Redux binding for React Router v4
Main features
:sparkles: Synchronize router state with redux store with uni-directional flow (history -> store -> router -> components).
:gift: Support React Router v4.
:sunny: Support functional component hot reloading while preserving state (with react-hot-reload v3).
:tada: Dispatching history methods (push
, replace
, go
, goBack
, goForward
) work for both redux-thunk and redux-saga.
:snowman: Nested children can access routing state such as current location directly with react-redux
's connect
.
:clock9: Support time traveling in Redux DevTools.
:gem: Support Immutable.js
:muscle: Support TypeScript
Installation
Using npm:
$ npm install --save connected-react-router
Or yarn:
$ yarn add connected-react-router
Usage
Step 1
- Create a
history
object. - Wrap the root reducer with
connectRouter
and supply the history
object to get a new root reducer. - Use
routerMiddleware(history)
if you want to dispatch history actions (ex. to change URL with push('/path/to/somewhere')
).
...
import { createBrowserHistory } from 'history'
import { applyMiddleware, compose, createStore } from 'redux'
import { connectRouter, routerMiddleware } from 'connected-react-router'
...
const history = createBrowserHistory()
const store = createStore(
connectRouter(history)(rootReducer),
initialState,
compose(
applyMiddleware(
routerMiddleware(history),
),
),
)
Step 2
- Wrap your react-router v4 routing with
ConnectedRouter
and pass history
object as a prop. - Place
ConnectedRouter
as children of react-redux
's Provider
.
...
import { Provider } from 'react-redux'
import { Route, Switch } from 'react-router'
import { ConnectedRouter } from 'connected-react-router'
...
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}> { /* place ConnectedRouter under Provider */ }
<div> { /* your usual react-router v4 routing */ }
<Switch>
<Route exact path="/" render={() => (<div>Match</div>)} />
<Route render={() => (<div>Miss</div>)} />
</Switch>
</div>
</ConnectedRouter>
</Provider>,
document.getElementById('react-root')
)
Now, it's ready to work!
Examples
See examples folder
FAQ
How to navigate with Redux action
with store.dispatch
import { push } from 'connected-react-router'
store.dispatch(push('/path/to/somewhere'))
in redux thunk
import { push } from 'connected-react-router'
export const login = (username, password) => (dispatch) => {
dispatch(push('/home'))
}
in redux saga
import { push } from 'connected-react-router'
import { put, call } from 'redux-saga/effects'
export function* login(username, password) {
yield put(push('/home'))
}
How to get current browser location (URL)
The current browser location can be accessed directry from the router state with react-redux
's connect
.
The location object composes of pathname, search (query string), and hash.
import { connect } from 'react-redux'
const Child = ({ pathname, search, hash }) => (
<div>
Child receives
<div>
pathname: {pathname}
</div>
<div>
search: {search}
</div>
<div>
hash: {hash}
</div>
</div>
)
const mapStateToProps = state => ({
pathname: state.router.location.pathname,
search: state.router.location.search,
hash: state.router.location.hash,
})
export default connect(mapStateToProps)(Child)
How to hot reload functional components
- Separate main app component to another file.
App.js
import React from 'react'
import { Route, Switch } from 'react-router'
import { ConnectedRouter } from 'connected-react-router'
const App = ({ history }) => (
<ConnectedRouter history={history}>
<div>
<Switch>
<Route exact path="/" render={() => (<div>Match</div>)} />
<Route render={() => (<div>Miss</div>)} />
</Switch>
</div>
</ConnectedRouter>
)
export default App
- Wrap the
App
component with AppContainer
from react-hot-loader
v3 as a top-level container.
index.js
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { AppContainer } from 'react-hot-loader'
import App from './App'
...
const render = () => {
ReactDOM.render(
<AppContainer> { /* AppContainer for hot reloading v3 */ }
<Provider store={store}>
<AppComponent history={history} /> { /* pass history object as props */ }
</Provider>
</AppContainer>,
document.getElementById('react-root')
)
}
render()
- Detect change and re-render with hot reload.
index.js
...
if (module.hot) {
module.hot.accept('./App', () => {
render()
})
}
Now, when you change any component that App
depends on, it will trigger hot reloading without losing redux state. Thanks react-hot-loader v3!
How to hot reload reducers
Detect change and replace with a new root reducer with router state
index.js
...
if (module.hot) {
module.hot.accept('./reducers', () => {
store.replaceReducer(connectRouter(history)(rootReducer))
})
}
How to support Immutable.js
- Use
combineReducers
from redux-immutable
to create the root reducer.
import { combineReducers } from 'redux-immutable'
...
const rootReducer = combineReducers({
...
})
...
- Import
ConnectedRouter
, routerMiddleware
, and connectRouter
from connected-react-router/immutable
instead of connected-react-router
.
import { ConnectedRouter, routerMiddleware, connectRouter } from 'connected-react-router/immutable'
- (Optional) Initialize state with
Immutabel.Map()
import Immutable from 'immutable'
...
const initialState = Immutable.Map()
...
const store = createStore(
connectRouter(history)(rootReducer),
initialState,
...
)
Build
npm run build
Generated files will be in lib
folder.
Contributors
See Contributors and Acknowledge.
License
MIT License