Created
October 24, 2022 16:19
-
-
Save biniama/dcc0a512cbb4b6dbecccea534bcc7ba5 to your computer and use it in GitHub Desktop.
PrivateRoute in ReactJS (from https://github.dev/The-Tech-Tutor/spring-react-login)
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 { Route, Switch } from "react-router-dom"; | |
import PrivateRoute from "../common/PrivateRoute"; | |
class App extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
authenticated: false, | |
currentUser: null, | |
loading: false | |
}; | |
} | |
render() { | |
if (this.state.loading) { | |
return <LoadingIndicator />; | |
} | |
return ( | |
<div className="app"> | |
<div className="app-top-box"> | |
<AppHeader authenticated={this.state.authenticated} onLogout={this.handleLogout} /> | |
</div> | |
<div className="app-body"> | |
<Switch> | |
<Route exact path="/" component={Home}></Route> | |
<PrivateRoute | |
path="/profile" | |
authenticated={this.state.authenticated} | |
currentUser={this.state.currentUser} | |
component={Profile} | |
></PrivateRoute> | |
<Route | |
path="/login" | |
render={props => <Login authenticated={this.state.authenticated} {...props} />} | |
> | |
</Route> | |
<Route path="/oauth2/redirect" component={OAuth2RedirectHandler}></Route> | |
<Route component={NotFound}></Route> | |
</Switch> | |
</div> | |
<Alert stack={{ limit: 3 }} timeout={3000} position="top-right" effect="slide" offset={65} /> | |
</div> | |
); | |
} | |
} | |
export default App; |
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, authenticated, ...rest }) => ( | |
<Route | |
{...rest} | |
render={props => | |
authenticated ? ( | |
<Component {...rest} {...props} /> | |
) : ( | |
<Redirect | |
to={{ | |
pathname: "/login", | |
state: { from: props.location } | |
}} | |
/> | |
) | |
} | |
/> | |
); | |
export default PrivateRoute; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment