Skip to content

Instantly share code, notes, and snippets.

@ooade
Last active April 6, 2017 11:32
Show Gist options
  • Save ooade/a49bf2c3978efaa0cc1e0e4601513cd3 to your computer and use it in GitHub Desktop.
Save ooade/a49bf2c3978efaa0cc1e0e4601513cd3 to your computer and use it in GitHub Desktop.
hoc in react with react-redux
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;
}
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);
}
@ooade
Copy link
Author

ooade commented Apr 6, 2017

Don't take the first approach(RequireAuth Component without Redux) if you plan on using SSR because of localstorage :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment