Skip to content

Instantly share code, notes, and snippets.

@gilbarbara
Last active November 28, 2019 18:01
Show Gist options
  • Save gilbarbara/ee0bdd22851bd897b864b0c57b4cb070 to your computer and use it in GitHub Desktop.
Save gilbarbara/ee0bdd22851bd897b864b0c57b4cb070 to your computer and use it in GitHub Desktop.
react-router v4 with redux
import React from 'react';
import { Router } from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';
const LOCATION_CHANGE = '@@router/LOCATION_CHANGE';
export const history = createBrowserHistory();
class ReduxRouter extends React.Component {
static propTypes = {
children: React.PropTypes.node.isRequired,
dispatch: React.PropTypes.func.isRequired,
};
componentDidMount() {
this.unsubscribe = history.listen(this.handleLocationChange);
}
componentWillUnmount() {
this.unsubscribe();
}
handleLocationChange = (location, action) => {
const { dispatch } = this.props;
dispatch({
type: LOCATION_CHANGE,
location,
action,
});
};
render() {
const { children } = this.props;
return (
<Router history={history}>
{children}
</Router>
);
}
}
export const { push, replace, go, goBack, goForward } = history;
export default ReduxRouter;
@gilbarbara
Copy link
Author

Setup

import ReduxRouter, { push, goBack } from './ReduxRouter';

@gilbarbara
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment