Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to login page in react router 4

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.

like image 403
Anshul Srivastava Avatar asked Jan 08 '19 12:01

Anshul Srivastava


People also ask

How do I redirect a user to login page in react?

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.

How do you redirect to last page after login in react?

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.


1 Answers

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>
like image 66
0xc14m1z Avatar answered Sep 22 '22 03:09

0xc14m1z