Last active
July 18, 2018 16:26
-
-
Save chodorowicz/c4d307029ec85df3f57681a08812a4bd to your computer and use it in GitHub Desktop.
React HOC example
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
/** base form */ | |
import React, { Component } from 'react'; | |
export default function(InnerComponent) { | |
class WrapperComponent extends Component { | |
render() { | |
return <InnerComponent {...this.props} /> | |
} | |
} | |
} | |
/** with some extras */ | |
import React, { Component } from 'react'; | |
import { connect } from 'react-redux'; | |
export default function(ComposedComponent) { | |
class Authentication extends Component { | |
static contextTypes = { | |
router: React.PropTypes.object | |
} | |
componentWillMount() { | |
if (!this.props.authenticated) { | |
this.context.router.push('/'); | |
} | |
} | |
componentWillUpdate(nextProps) { | |
if (!nextProps.authenticated) { | |
this.context.router.push('/'); | |
} | |
} | |
render() { | |
return <ComposedComponent {...this.props} /> | |
} | |
} | |
function mapStateToProps(state) { | |
return { authenticated: state.authenticated }; | |
} | |
return connect(mapStateToProps)(Authentication); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment