React Router history.goBack() is not working properly?

Viewed 653

I'm using Electron React Boilerplate for creating a app. I'm facing a weird issue with react-router-dom.

My application code (simplified):

In App.tsx

      ...
         {user.isLoggedIn ? <Dashboard/> : <LoginComponent/>}
       ...

LoginComponent contains authentication logic.

In Dashboard component, I have react-router setup, as follows:

...other imports...
import {
  Switch,
  Route,
  BrowserRouter as Router
} from 'react-router-dom';

  ...some code...
  <Router>
    <Switch>
          <Route path="/" exact>
            <SomeComponent />
          </Route>
          <Route path="/upload" exact>
            <UploadPage />
          </Route>
          <Route path="/info" exact>
            <InfoPage />
          </Route>

          // added for testing, explained below
          <Route path="/" >
            <TestComponent />
          </Route>
  </Router>
...some code..

In UploadPage:

 ...
 const history = useHistory();
 ...

 <Button onClick={() => history.push('/info')}>Go To Info</Button>}
 
 ...

In InfoPage:

 ...
 const history = useHistory();
 ...

 <Button onClick={() => history.goBack()}>Go Back</Button>} // Instead of going back to Upload Page, it opens a blank page
                                     
 
 ...

Issue:
In InfoPage, When user click on Go Back button, instead of going back to UploadPage, it redirects to a blank page. To caught any non-matching route, I added a <Route path="/" > <TestComponent /> </Route> as a last route in Switch statement of Dashboard component. Now, when user click on Go Back button, it redirects to TestComponent. In TestComponet, when I print url and path (const {url, path} = useRouteMatch()) in console, both are /.

I'm using:

    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-router-dom": "^5.2.0",

Any help is appreciated.


Update

I added, history.listen((a, b) => console.log(JSON.stringify(a), JSON.stringify(b))) to check what's happening. On click of Go to Info button, it logs {"pathname":"/info","search":"","hash":"","key":"ljso73"} "PUSH" and on click of Go Back button, it logs {"pathname":"/D:/upload","search":"","hash":"","key":"lyhxi5"} "POP", which is strange. My project is placed in D: directory but inside some folders (not in root of D: directory).

0 Answers
Related