Skip to content Skip to sidebar Skip to footer

React Router V5: History.push() Changes The Address Bar, But Does Not Change The Page

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

Solution 1:

Instead 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';
importReactfrom'react';

const history = createBrowserHistory();


exportdefaultfunctionApp() {
    return (
        <Routerhistory={history}><Switch><Routepath="/"exactcomponent={() =><h1>HomePage</h1>} />
                <Routepath="/login"exactcomponent={Login} /><Routerender={() =><h1>404: not found</h1>} />
            </Switch></Router>
    );
}


functionLogin() {
  React.useEffect(() => {
    history.push('/pageafterlogin')
  }, [])

  return<h1>Login page</h1>
}

Solution 2:

import { Router } from'react-router-dom';
import { createBrowserHistory } from'history';
importReactfrom'react';
const history = createBrowserHistory();


exportdefaultfunctionMyApp() {
    return (
        <Routerhistory={history}></Router>
    );
}

Post a Comment for "React Router V5: History.push() Changes The Address Bar, But Does Not Change The Page"