React Router 6 - back button doesn't work after initial navigation away from start page

Viewed 552

When creating a standard Router setup with Router v6, if a user navigates away from the initial page ("/") then hits the back button, the browser won't return them to the original page.

The back button WILL still become "grayed out", though, as though it believes it actually did go back to the previous page. If you navigate TWO pages away, however, hitting back will return to the middle page. For example, if the user navigates:

"/" -> "/page1" -> "/page2"

and then proceeds to hit the back button, they will land back on "/page1". However, if they hit the back button again, the browser will stay on "/page1".

So it seems to me router is somehow not adding the initial "/" page to the history stack; rather, it is adding whichever first page the user navigates to twice.

At first I thought I must be doing something wrong, but I checked out a few of the public router 6 templates on codesandbox and they all have the same problem! Somehow nobody else seems to have noticed, or at least reported, this issue, or no amount of google searching is turning said reports up.

Here are some (abridged) code samples of my specific case, though I'm not sure what good they are considering the problem seems universal as far as I can tell.

App.tsx:

export default function(){
  return (
    <div className="app">
      <Routes>
        <Route path="/" element={<Home image={images[0]} />} />
        <Route path="/About" element={<About image={images[1]} />} />
        <Route path="/Contact" element={<Contact />} />
      </Routes>
    </div>
  )
}

The containing BrowserRouter is in index.tsx:

ReactDOM.render(
  <StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </StrictMode>,
  rootElement
);

Links in the "Home" component (Home.tsx):

export default function ({ image }: HomeProps) {
  return (
    <>
      <div className="home">
        {<img src={image.src} alt="pixelMike" className="profile_image" />}
        <div className="link_container">
          <Link to="About" className="nav_link">
            Who am I?
          </Link>
        </div>
        <div className="link_container">
          <Link to="Contact" className="nav_link">
            Speak to me.
          </Link>
        </div>
      </div>
    </>
  );
}

As you can see, I'm working in typescript if that makes a difference (though I would think it shouldn't).

0 Answers
Related