PrivateRoute.jsx 965B

1234567891011121314151617181920212223242526
  1. import React from 'react'
  2. import PropTypes from 'prop-types'
  3. import { connect } from 'react-redux'
  4. import { Route, Redirect, withRouter } from 'react-router-dom'
  5. // component inspired from https://reacttraining.com/react-router/web/example/auth-workflow
  6. // /!\ you shall destruct props.component otherwise you get a warning:
  7. // "You should not use <Route component> and <Route render> in the same route; <Route render> will be ignored
  8. const PrivateRoute = ({ component: Component, ...rest }) => (
  9. <Route {...rest} render={props => rest.user.isLoggedIn
  10. ? <Component {...props} />
  11. : <Redirect to={{pathname: '/login', state: {from: props.location}}} />
  12. } />
  13. )
  14. const mapStateToProps = ({ user }) => ({ user })
  15. export default withRouter(connect(mapStateToProps)(PrivateRoute))
  16. PrivateRoute.propTypes = {
  17. component: PropTypes.func.isRequired,
  18. user: PropTypes.shape({ // user is get with redux connect
  19. isLoggedIn: PropTypes.bool.isRequired
  20. })
  21. }