Last active
March 22, 2023 00:19
-
-
Save jordanrios94/f9ec406a5ef4a5cb25f0fc7796441c10 to your computer and use it in GitHub Desktop.
HOC Scaffold
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 { connect } from 'react-redux'; | |
export default (ChildComponent) => { | |
class ComposedComponent extends Component { | |
// Our component just got rendered | |
componentDidMount() { | |
this.shouldNavigateAway(); | |
} | |
// Our component just got updated | |
componentDidUpdate() { | |
this.shouldNavigateAway(); | |
} | |
shouldNavigateAway() { | |
if (!this.props.auth) { | |
this.props.history.push('/'); | |
} | |
} | |
function mapStateToProp(state) { | |
return { auth: state.auth } | |
} | |
render() { | |
return <ChildComponent {...this.props} />; | |
}; | |
} | |
return connect(mapStateToProps)(ComposedComponent); | |
}; | |
// Imagine we are in CommentBox.js | |
/* | |
import requireAuth from 'components/requireAuth' | |
class CommentBox {} | |
export default requireAuth(CommentBox); | |
*/ | |
// Imagine we are in App.js | |
/* | |
import CommentBox from './CommentBox'; | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment