Last active
April 6, 2017 11:32
-
-
Save ooade/a49bf2c3978efaa0cc1e0e4601513cd3 to your computer and use it in GitHub Desktop.
hoc in react with react-redux
This file contains hidden or 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'; | |
export default function(ComposedComponent) { | |
class Auth extends Component { | |
static contextTypes = { | |
router: React.PropTypes.object | |
} | |
componentWillMount() { | |
if (!localstorage.token) { | |
this.context.router.push('/'); | |
} | |
} | |
componentWillUpdate() { | |
if (!localstorage.token) { | |
this.context.router.push('/'); | |
} | |
} | |
render() { | |
return <ComposedComponent {...this.props} /> | |
} | |
} | |
return Auth; | |
} |
This file contains hidden or 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 function(ComposedComponent) { | |
class Auth extends Component { | |
static contextTypes = { | |
router: React.PropTypes.object | |
} | |
componentWillMount() { | |
if (!this.props.auth) { | |
this.context.router.push('/'); | |
} | |
} | |
componentWillUpdate(nextProps) { | |
if (!nextProps.auth) { | |
this.context.router.push('/'); | |
} | |
} | |
render() { | |
return <ComposedComponent {...this.props} /> | |
} | |
} | |
function mapStateToProps({ auth }) { | |
return { auth: auth.isAuth }; | |
} | |
return connect(mapStateToProps)(Auth); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't take the first approach(RequireAuth Component without Redux) if you plan on using SSR because of localstorage :)