Skip to content

Instantly share code, notes, and snippets.

@sungwoncho
Created July 5, 2016 07:09
Show Gist options
  • Save sungwoncho/5c069831ea4cd01dd2be05121f4689ef to your computer and use it in GitHub Desktop.
Save sungwoncho/5c069831ea4cd01dd2be05121f4689ef to your computer and use it in GitHub Desktop.
import React from 'react';
import { connect } from 'react-redux';
/**
* A higher order function that returns a function whose argument is the component
* to be wrapped.
*
* usage example:
* const EnsureLoggedIn = AuthWrapper();
* <EnsureLoggedIn(Profile) />
*/
export default function authWrapper(options = {}) {
return (WrappedComponent) => {
class AuthComponent extends React.Component {
render() {
const { user } = this.props;
if (options.guest) {
return (
user ? <div>You are already logged in!</div> : <WrappedComponent />
);
} else {
return (
user ? <WrappedComponent /> : <div>Please sign in</div>
);
}
}
}
if (WrappedComponent.reduxAsyncConnect) {
AuthComponent.reduxAsyncConnect = WrappedComponent.reduxAsyncConnect;
}
return connect(
(state) => ({
user: state.auth.user
})
)(AuthComponent);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment