Skip to content

Instantly share code, notes, and snippets.

@dolfelt
Created October 27, 2016 13:07
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dolfelt/304e4a99b6f413d609994732a33b5906 to your computer and use it in GitHub Desktop.
Save dolfelt/304e4a99b6f413d609994732a33b5906 to your computer and use it in GitHub Desktop.
ConnectedRouter for using react-router v4 with Redux
import React, { Component, PropTypes } from 'react';
import createBrowserHistory from 'history/createBrowserHistory';
import History from 'react-router/History';
import StaticRouter from 'react-router/StaticRouter';
import { LOCATION_CHANGE } from './routerReducer';
class DispatchingRouter extends Component {
static propTypes = {
store: PropTypes.object,
history: PropTypes.object,
action: PropTypes.string,
location: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
basename: PropTypes.string,
}
constructor(props) {
super(props);
this.handleLocationChange(props);
}
componentWillReceiveProps(nextProps) {
this.handleLocationChange(nextProps);
}
handleLocationChange = ({ store, action, location }) => {
store.dispatch({
type: LOCATION_CHANGE,
payload: { action, location },
});
}
render() {
const { history, action, location, basename, ...props } = this.props;
return (
<StaticRouter
action={action}
location={location}
basename={basename}
onPush={history.push}
onReplace={history.replace}
blockTransitions={history.block}
{...props}
/>
);
}
}
const ConnectedRouter = ({
store,
basename,
forceRefresh,
getUserConfirmation,
keyLength,
...routerProps,
}, { store:contextStore }) => {
return (
<History
createHistory={ createBrowserHistory }
historyOptions={{
basename,
forceRefresh,
getUserConfirmation,
keyLength,
}}
>
{({ history, action, location }) => {
return (
<DispatchingRouter
store={contextStore || store}
history={history}
action={action}
location={location}
basename={basename}
{...routerProps}
/>
);
}}
</History>
);
};
ConnectedRouter.contextTypes = {
store: PropTypes.object,
};
ConnectedRouter.propTypes = {
store: PropTypes.object,
basename: PropTypes.string,
forceRefresh: PropTypes.bool,
getUserConfirmation: PropTypes.func,
keyLength: PropTypes.number,
};
export default ConnectedRouter;
export const LOCATION_CHANGE = '@@router/LOCATION_CHANGE';
const initialState = {
location: null,
};
export default function routerReducer(state = initialState, { type, payload } = {}) {
if (type === LOCATION_CHANGE) {
return { ...state, ...payload };
}
return state;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment