-
-
Save vikbert/58ee8826d61a300144dd87b4772709b5 to your computer and use it in GitHub Desktop.
React/Redux Auth with Private Route Component
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 { Route, Redirect } from 'react-router-dom'; | |
const PrivateRoute = ({ component: Component, authed, ...rest }) => ( | |
<Route | |
{...rest} | |
render={props => ( | |
authed | |
? <Component {...props} /> | |
: <Redirect to="/login" /> | |
)} | |
/> | |
); | |
export default PrivateRoute; |
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, { Component } from 'react'; | |
import { connect } from 'react-redux'; | |
import { BrowserRouter, Route } from 'react-router-dom'; | |
import * as actions from '../actions'; | |
import Dashboard from '../components/Dashboard'; | |
import UserAuth from '../components/UserAuth'; | |
import PrivateRoute from '../components/PrivateRoute'; | |
class Routes extends Component { | |
componentDidMount() { | |
console.log('==== Routes mounted!'); | |
} | |
render() { | |
console.log('Routes props', this.props.currentUser); | |
return ( | |
<BrowserRouter> | |
<div> | |
<Route exact path="/login" component={UserAuth} /> | |
<Route exact path="/signup" component={UserAuth} /> | |
<PrivateRoute exact path="/" component={Dashboard} authed={this.props.currentUser} /> | |
</div> | |
</BrowserRouter> | |
); | |
} | |
} | |
const mapStateToProps = state => ({ currentUser: state.userAuth }); | |
export default connect(mapStateToProps, actions)(Routes); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment