Skip to content

Instantly share code, notes, and snippets.

@Nifled
Last active August 22, 2018 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nifled/aa824a5a4120c36dcaeacdb6bcc69fa2 to your computer and use it in GitHub Desktop.
Save Nifled/aa824a5a4120c36dcaeacdb6bcc69fa2 to your computer and use it in GitHub Desktop.
React Redux protected routes
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>
)
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