Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJs protected route redirect/refresh issue

Using react + react-router-dom:

import React from 'react';
import { Switch, Route, Redirect } from 'react-router-dom'; 

And protecting a route by this:

Router

const Router = () => {
    return (
        <Switch>
            <PrivateRoute exact path='/Panel' component={Panel}></PrivateRoute>
            <Route exact path='/Register' component={Register}></Route>
            <Route exact path='/Login' component={Login}></Route>
        </Switch>
    );
};

const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route
        {...rest}
        render={props =>
            Auth.getAuth() ? (
                <Component {...props} />
            ) : (
                <Redirect
                    to={{
                        pathname: "/Login"
                    }}
                />
            )
        }
    />
);

Auth

const Auth = {
    isAuthenticated: false,
    authenticate() {
        this.isAuthenticated = true;
    },
    signout() {
        this.isAuthenticated = false;
    },
    getAuth() {
        return this.isAuthenticated;
    }
};

So this working fine and user easily can login, logout, but the problem is when user logged I want to redirect user to /Panel route so I tried:

window.location.href = "/Panel"

OR:

this.props.history.push('/Panel')

Both redirect to /Login again too fast, but If I click on Panel link it going to Panel route. Second problem is when I refresh page on this address /Panel it bring me back to /Login again. So what I want to solve are:

  1. How to redirect to protected route?
  2. How to avoid redirect when refresh page on protected route? If I type this address and enter it not working too.

Already seen this topic and tried but no success:

What is the best way to redirect a page using React Router?

like image 777
tour travel Avatar asked Oct 31 '19 07:10

tour travel


People also ask

Does react redirect refresh page?

react-router-dom allows us to navigate through different pages on our app with/without refreshing the entire component. By default, BrowserRouter in react-router-dom will not refresh the entire page.

How do I restrict routes in ReactJS?

To restrict access to routes in React Router, we set the render prop to a function that renders the component we want according to the condition we're checking. import { Route, Redirect } from "react-router"; <Route exact path="/" render={() => (loggedIn ?

What is the best way to redirect a page using react router?

To redirect to another page on button click in React: Use the useNavigate() hook, e.g. const navigate = useNavigate(); . Call the navigate() function, passing it the path - navigate('/about') .

How do you know when a route changes in react?

To detect route change with React Router, we can use the useLocation hook. import { useEffect } from "react"; import { useLocation } from "react-router-dom"; const SomeComponent = () => { const location = useLocation(); useEffect(() => { console. log("Location changed"); }, [location]); //... };


1 Answers

For the first question:

You can keep the url in the state like this so that after login you can redirect to.

<Redirect
  to={{
    pathname: "/login",
    state: { from: props.location }
  }}
/>

And in Login component, after successfull login you can redirect to:

const { state } = this.props.location;
window.location = state ? state.from.pathname : "/";

For the second question:

one alternative solution would be keeping the login state in localStorage so that after refreshes the app can read from there. This is generally done sending a jsonwebtoken from login api to the client, and saving the token to the localStorage.

like image 72
SuleymanSah Avatar answered Nov 03 '22 07:11

SuleymanSah