Skip to content

Instantly share code, notes, and snippets.

@upq
Last active May 20, 2016 13:04
Show Gist options
  • Save upq/6543070ceacbaa368e2a431dc5782779 to your computer and use it in GitHub Desktop.
Save upq/6543070ceacbaa368e2a431dc5782779 to your computer and use it in GitHub Desktop.
Composed React Component to handle protected routes.
import React, { PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './ProtectedRoute.scss';
import RequireAuthentication from '../../components/Authentication/RequireAuthentication';
const title = 'ProtectedRoute';
function ProtectedRoute(props, context) {
context.setTitle(title);
return (
<div className={s.root}>
<div className={s.container}>
This Information is protected
</div>
</div>
);
}
ProtectedRoute.contextTypes = { setTitle: PropTypes.func.isRequired };
export default withStyles(s)(RequireAuthentication(ProtectedRoute));
import React, { Component } from 'react';
import { connect } from 'react-redux';
// A login form component or what ever you would like to fall back to if the
// the user is not authenticated
import LoginForm from './Forms/LoginForm';
export default function(ComposedComponent){
class Authentication extends Component {
render () {
// Check your redux store for an isAuthenticated attribute
// If is authenticated return the composed component
if (this.props.authenticationStore.isAuthenticated) {
return <ComposedComponent {...this.props} />
}
// Not authenticated
else {
return (
<LoginForm/>
);
}
}
}
// Map state to props
function mapStateToProps(state){
return { authenticationStore: state.authenticationStore }
}
return connect(mapStateToProps)(Authentication);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment