Last active
January 11, 2017 03:08
-
-
Save tomkis/9cbc314551f8f14243a7ff92f84e959f to your computer and use it in GitHub Desktop.
react-router-redux with react-router 4.x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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