Skip to content

Instantly share code, notes, and snippets.

@tomkis
Last active January 11, 2017 03:08
Show Gist options
  • Save tomkis/9cbc314551f8f14243a7ff92f84e959f to your computer and use it in GitHub Desktop.
Save tomkis/9cbc314551f8f14243a7ff92f84e959f to your computer and use it in GitHub Desktop.
react-router-redux with react-router 4.x
import React, { Component } from 'react';
import Match from 'react-router/Match';
import { connect } from 'react-redux';
import * as ActionTypes from '../constants/actionTypes';
import buildActionCreators from '../helpers/buildActionCreators';
const EMPTY_PROPS = {};
const createMountableComponent = (Cmp, routeId) => connect(
() => EMPTY_PROPS,
buildActionCreators({
onMount: ActionTypes.ROUTE_HAS_CHANGED
})
)(class MountableComponent extends Component {
componentWillMount() {
this.props.onMount(routeId);
}
render() {
return <Cmp {...this.props} />;
}
});
class ReduxMatch extends Component {
constructor(props) {
super(props);
this.state = { mountableComponent: null };
}
componentWillMount() {
this.setState({
mountableComponent: createMountableComponent(this.props.component, this.props.routeId)
});
}
componentWillReceiveProps(nextProps) {
if (nextProps.component !== this.props.component || nextProps.routeId !== this.props.routeId) {
this.setState({
mountableComponent: createMountableComponent(nextProps.component, nextProps.routeId)
});
}
}
render() {
if (this.state.mountableComponent) {
return <Match {...this.props} component={this.state.mountableComponent} />;
} else {
return false;
}
}
}
export default ReduxMatch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment