Skip to content

Instantly share code, notes, and snippets.

@mikespencer
Created September 19, 2017 21:37
Show Gist options
  • Save mikespencer/0e5d733f2836c89f3a7753187e0c5a35 to your computer and use it in GitHub Desktop.
Save mikespencer/0e5d733f2836c89f3a7753187e0c5a35 to your computer and use it in GitHub Desktop.
Redirect HOC's
const loggedInOrRedirect = (options = {}) => WrappedComponent => {
class LoggedInOrRedirect extends React.Component {
static displayName = `LoggedInOrRedirect(${getDisplayName(
WrappedComponent
)})`;
render() {
const { self, ...passThroughProps } = this.props;
if (self.id /* or however we check if someone is logged in */) {
return <Redirect to={options.to} />;
} else {
return <WrappedComponent {...passThroughProps} />;
}
}
}
return connect(state => ({ self: selfSelector }), null)(
LoggedInOrRedirect
);
};
// Usage (w/ other HOC's, such as react-redux connect, custom adminOrRedirect, etc)
const enhance = compose(
loggedInOrRedirect({ to: 'https://www.meetup.com/pro/' }),
adminOrRedirect({ to: 'https://www.meetup.com/pro/' }),
connect(...), // <- normal connect mapStateToProps, mapDispatchToProps stuff,
withIntl(...),
);
export default enhance(MyContainer);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment