Skip to content

Instantly share code, notes, and snippets.

@wuct
Created December 22, 2015 06:22
Show Gist options
  • Save wuct/d9e1ee3b335b2fa6ef5d to your computer and use it in GitHub Desktop.
Save wuct/d9e1ee3b335b2fa6ef5d to your computer and use it in GitHub Desktop.
An authorization high-order-component using recompose, redux and react-router.
import { emptyObject } from 'fbjs/lib/emptyObject';
import { connect } from 'react-redux';
import { pushState } from 'redux-router';
import pure from 'recompose/pure';
import defaultProps from 'recompose/defaultProps';
import doOnReceiveProps from 'recompose/doOnReceiveProps';
import renderNothing from 'recompose/renderNothing';
import renderComponent from 'recompose/renderComponent';
import branch from 'recompose/branch';
import compose from 'recompose/compose';
export default function(BaseComponent) {
return compose(
connect(
({ auth }) => ({ auth }),
{ pushState }
),
pure,
defaultProps({ auth: emptyObject }),
doOnReceiveProps(props => {
if (!props.auth.token) {
props.pushState(null, `/login?next=${location.pathname}`);
}
}),
branch(
props => props.auth.token,
renderComponent(BaseComponent),
renderNothing,
)
)(BaseComponent);
}
@wuct
Copy link
Author

wuct commented Dec 22, 2015

For example, we can use it in our route.

  <Route path="/" component={App}>
    <IndexRoute component={AuthorizationHOC(DashboardPage)} />
    <Route path="/login" component={LoginForm} />
  </Route>

@wuct
Copy link
Author

wuct commented Dec 22, 2015

This example is derived from joshgeller/react-redux-jwt-auth-example.

@jackypan1989
Copy link

Really nice example.

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