Skip to content

Instantly share code, notes, and snippets.

@aliaksandr-master
Last active December 1, 2016 11:50
Show Gist options
  • Save aliaksandr-master/feea782f4b2958000bf5c2580fe1a10d to your computer and use it in GitHub Desktop.
Save aliaksandr-master/feea782f4b2958000bf5c2580fe1a10d to your computer and use it in GitHub Desktop.
Connect ReactRouterV4 to Redux
import React, { Component, PropTypes } from 'react';
import { BASE_URL } from '../config';
import createBrowserHistory from 'history/createBrowserHistory';
import cloneDeep from 'lodash/cloneDeep';
import once from 'lodash/once';
import StaticRouter from 'react-router/StaticRouter';
const history = createBrowserHistory({
basename: BASE_URL
});
const ACTION_LOCATION_CHANGE = '@LOCATION_CHANGE';
const changeState = (location, action) => ({
type: ACTION_LOCATION_CHANGE,
payload: { action, location }
});
const initialState = cloneDeep({
action: String(history.action),
location: history.location
});
export const routerReducer = (state = initialState, action) => {
if (action.type === ACTION_LOCATION_CHANGE) {
return { ...action.payload };
}
return state;
};
class HistoryRouter extends Component {
static contextTypes = {
store: PropTypes.shape({ dispatch: PropTypes.func.isRequired })
};
static propTypes = {
action: PropTypes.oneOf([ 'REPLACE', 'POP', 'PUSH' ]),
location: PropTypes.object.isRequired,
children: PropTypes.node.isRequired
};
componentWillMount () {
const { store } = this.context;
this._historyCleanupListener = once(history.listen((location, action) => {
store.dispatch(changeState(location, action));
}));
}
componentWillUnmount () {
this._historyCleanupListener();
}
render () {
const { children, action, location } = this.props;
return (
<StaticRouter
action={action}
location={location}
basename={BASE_URL}
onPush={history.push}
onReplace={history.replace}
blockTransitions={history.block}
>{children}</StaticRouter>
);
}
}
export default HistoryRouter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment