Last active
August 22, 2018 19:12
-
-
Save Nifled/aa824a5a4120c36dcaeacdb6bcc69fa2 to your computer and use it in GitHub Desktop.
React Redux protected routes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const App = ({ location, isAuthenticated }) => ( | |
<div className='ui container'> | |
{ isAuthenticated && <TopNavigation /> } | |
<Route location={location} path='/' exact component={HomePage} /> | |
<Route location={location} path='/confirmation/:token' exact component={ConfirmationPage} /> | |
<UserRoute location={location} path='/dashboard' exact component={DashboardPage} /> | |
<UserRoute location={location} path='/books/new' exact component={NewBookPage} /> | |
</div> | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import { connect } from 'react-redux' | |
import { Route, Redirect } from 'react-router-dom' | |
import PropTypes from 'prop-types' | |
// Higher order component. Basically, we'll take the 'react-router' Route component | |
// and wrap it with a HOC to lock the component for authenticated users only. | |
const UserRoute = ({ isAuthenticated, component: Component, ...props }) => ( | |
<Route {...props} render={props => | |
isAuthenticated ? <Component {...props} /> : <Redirect to="/" />} | |
/> | |
) | |
UserRoute.propTypes = { | |
component: PropTypes.func.isRequired, | |
isAuthenticated: PropTypes.bool.isRequired | |
} | |
function mapStateToProps(state) { | |
return { | |
isAuthenticated: !!state.user.token | |
} | |
} | |
export default connect(mapStateToProps)(UserRoute) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment