Skip to content

Instantly share code, notes, and snippets.

@thedanielforum
Created April 4, 2019 09:26
Show Gist options
  • Save thedanielforum/c2f156df42dbb54699d1e98fb6b685a7 to your computer and use it in GitHub Desktop.
Save thedanielforum/c2f156df42dbb54699d1e98fb6b685a7 to your computer and use it in GitHub Desktop.
React HOC for enforcing authentication on react-router routes.
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
export default function (ComposedComponent) {
class Authenticate extends React.Component {
static propTypes = {
isAuthenticated: PropTypes.bool.isRequired,
}
static contextTypes = {
router: PropTypes.shape({
history: PropTypes.shape({
push: PropTypes.func.isRequired,
}).isRequired,
}).isRequired,
}
componentWillMount() {
if (!this.props.isAuthenticated) {
this.context.router.history.push('/login');
}
}
render() {
return (
<ComposedComponent {...this.props} />
);
}
}
const mapStateToProps = state => ({
isAuthenticated: state.Auth.isAuthenticated,
});
return connect(mapStateToProps)(Authenticate);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment