'How to go to another route using <Redirect> on componentDidMount?
I'm trying to redirect user to /login if he isn't authenticated.
To do so, I'm checking if the user is authenticated in componentDidMount()
and if he isn't I'm redirecting him to /login
using the <Redirect to="/login"/>
balise.
The problem is that I have this error: You should not use <Redirect> outside a <Router>
, despite the fact that I am in a <BrowserRouter>
Here is my App.js
import React from 'react';
import {BrowserRouter, Route, Switch} from "react-router-dom";
import MainPage from "./pages/main-page/main-page";
import LoginPage from "./pages/login-page/login-page";
import PrivateRoute from "./components/private-route";
function App() {
return (
<BrowserRouter>
<Switch>
<PrivateRoute exact path="/" component={MainPage}/>
<Route path="/login" component={LoginPage}/>
</Switch>
</BrowserRouter>
);
}
export default App;
Here is my main-page.js
import React from 'react';
import authManager from "../../services/auth";
import Redirect from "react-router/modules/Redirect";
export default class MainPage extends React.Component{
state = {
loggedIn: false,
};
componentDidMount() {
authManager.isAuthenticate((res) => {
if (res.data)
this.setState({loggedIn: true})
}).then()
}
render() {
if (!this.state.loggedIn)
return <Redirect to='/login'/>;
return (
<div>
</div>
)
}
}
And here is my private-route.js
import { Route, Redirect } from 'react-router-dom';
import React from "react";
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
localStorage.getItem('isLoggedIn') === 'true'
? <Component {...props}/>
: <Redirect to='/login'/>
)} />
);
export default PrivateRoute;
Solution 1:[1]
This code for works fine, the problem is that I'm importing the <Redirect>
from 'react-router/modules/Redirect'
instead of using 'react-router-dom'
.
To make this code work you just have to replace in main-page.js:
import Redirect from "react-router/modules/Redirect";
to
import { Redirect } from 'react-router-dom';
Solution 2:[2]
import { Navigate } from 'react-router-dom';
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
localStorage.getItem('isLoggedIn') === 'true'
? <Component {...props}/>
: <Navigate to="/login" />
)} />
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Loufi |
Solution 2 | Ahmed amani |