I am trying to redirect a user to a new page if a login is successful in my React app. The redirect is called from the auth service which is not a component. To access the history object outside of my component I followed this example in the React Router FAQ. However, when I call history.push('/pageafterlogin')
, the page is not changed and I remain on the login page (based on my Switch
I would expect to end up on the 404
page). The URL in the address bar does get changed to /pageafterlogin
but the page is not changed from the login page. No errors appear in the console or anything else to indicate my code does not work.
How can I make history.push()
also change the page the user is on?
// /src/history.js
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
// /src/App.js
...
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import history from './history';
function App() {
return (
<Router history={history}>
<Switch>
<Route path="/" exact component={HomePage} />
<Route path="/login" exact render={() => <FormWrapper><LoginForm /></FormWrapper>} />
<Route render={() => <h1>404: not found</h1>} />
</Switch>
</Router>
);
}
export default App;
// src/services/auth.service.js
import axios from 'axios';
import history from '../history';
const API_URL = '...';
class AuthService {
login(username, password) {
return axios.post(API_URL + 'login', {
username,
password
}).then(res => {
if (res.status === 200) {
localStorage.setItem('user', JSON.stringify(res.data));
history.push('/pageafterlogin');
}
});
}
}
I am trying to redirect a user to a new page if a login is successful in my React app. The redirect is called from the auth service which is not a component. To access the history object outside of my component I followed this example in the React Router FAQ. However, when I call history.push('/pageafterlogin')
, the page is not changed and I remain on the login page (based on my Switch
I would expect to end up on the 404
page). The URL in the address bar does get changed to /pageafterlogin
but the page is not changed from the login page. No errors appear in the console or anything else to indicate my code does not work.
How can I make history.push()
also change the page the user is on?
// /src/history.js
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
// /src/App.js
...
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import history from './history';
function App() {
return (
<Router history={history}>
<Switch>
<Route path="/" exact component={HomePage} />
<Route path="/login" exact render={() => <FormWrapper><LoginForm /></FormWrapper>} />
<Route render={() => <h1>404: not found</h1>} />
</Switch>
</Router>
);
}
export default App;
// src/services/auth.service.js
import axios from 'axios';
import history from '../history';
const API_URL = '...';
class AuthService {
login(username, password) {
return axios.post(API_URL + 'login', {
username,
password
}).then(res => {
if (res.status === 200) {
localStorage.setItem('user', JSON.stringify(res.data));
history.push('/pageafterlogin');
}
});
}
}
Share
Improve this question
edited Nov 11, 2021 at 10:22
ouflak
2,50410 gold badges45 silver badges52 bronze badges
asked Aug 24, 2020 at 3:10
No stupid questionsNo stupid questions
4851 gold badge14 silver badges40 bronze badges
5
|
5 Answers
Reset to default 5Instead of using BrowserRouter
, use Router
from react-router-dom
You could see the example here
import { Router, Route, Switch, useHistory, create } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import React from 'react';
const history = createBrowserHistory();
export default function App() {
return (
<Router history={history}>
<Switch>
<Route path="/" exact component={() => <h1>HomePage</h1>} />
<Route path="/login" exact component={Login} />
<Route render={() => <h1>404: not found</h1>} />
</Switch>
</Router>
);
}
function Login() {
React.useEffect(() => {
history.push('/pageafterlogin')
}, [])
return <h1>Login page</h1>
}
If you are looking for a solution to this in 2022 and are using React V18+, the solution is that React v18 does not work well with react-router-dom v5.
I have not tried with react-router-dom v6 yet, but downgrading to React V17 solved the issue for me.
I removed StrictMode
and it solved the problem
import { Router } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import React from 'react';
const history = createBrowserHistory();
export default function MyApp() {
return (
<Router history={history}></Router>
);
}
I had the same problem when I hadn't specified the vesion of 'history'. You need to use a 4.x version with Router 5.x. For example, I use React v18, history v4.7.2 and react-router-dom v5.3.3 and it works fine. Try
npm i [email protected]
history
is passed to the Router component and the Routes are inside a Switch so even if/pageafterlogin
isn't defined it should default to the 404 page. – No stupid questions Commented Aug 24, 2020 at 3:14BrowserRouter
you need to importRouter
... If you open the console you'll see -Warning: <BrowserRouter> ignores the history prop. To use a custom history, use import { Router } instead of import { BrowserRouter as Router }
. – SakoBu Commented Aug 24, 2020 at 4:03BrowserRouter
andRouter
that would have an impact elsewhere in my code? – No stupid questions Commented Aug 24, 2020 at 4:04BrowserRouter
- reactrouter.com/web/api/BrowserRouterRouter
- reactrouter.com/web/api/Router (you can see it takes the history prop) There are alsoHashRouter
,MemoryRouter
etc... – SakoBu Commented Aug 24, 2020 at 4:08