I am new to react and still learning my way around. I am creating a single page app where the user is redirected to the login page if he is not logged in. React has a Redirect component and I am not sure how to use it.
Following is my app.js :-
import React, { Component } from 'react';
import { Route, Switch, Redirect } from 'react-router-dom';
import Login from './components/login/login.js'
import Protected from './components/protected/protected.js'
import './App.css';
class App extends Component {
state = {
loggedIn: false // user is not logged in
};
render() {
return (
<Switch>
<Route path="/protected" component={Protected}/>
<Route path="/login" component={Login}/>
</Switch>
);
}
}
export default App;
In the above scenario, I want the user to be redirected to the /login
page if the state loggedIn
is false or else it should go to the /protected
page.
Redirect User to Login Page Using Navigateimport { Navigate } from "react-router-dom"; To redirect unauthenticated users, use it as follows. The Navigate component is a declarative API. It relies on a user event, which in this case is authentication to cause a state change and consequently cause a component re-render.
There are two easy ways of doing this in React router v6, passing the previous location in the link state or just with the useNavigate hook.
I usually create a PrivateRoute
component that checks if the user is logged in (via prop, redux, localstorage or something).
Something like:
const PrivateRoute = ({ isLoggedIn, ...props }) =>
isLoggedIn
? <Route { ...props } />
: <Redirect to="/login" />
In the router I then use it for my, well, private routes :)
<Switch>
<PrivateRoute isLoggedIn={ this.state.loggedIn } path="/protected" component={Protected} />
<Route path="/login" component={Login}/>
</Switch>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With