Skip to content

Instantly share code, notes, and snippets.

@chodorowicz
Last active July 18, 2018 16:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chodorowicz/c4d307029ec85df3f57681a08812a4bd to your computer and use it in GitHub Desktop.
Save chodorowicz/c4d307029ec85df3f57681a08812a4bd to your computer and use it in GitHub Desktop.
React HOC example
/** 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