Unable to go back on React Router v6

Viewed 1745

I am experimenting with react-router-dom-6 and I have trouble going back to previous pages.

The sample app can Go Back from the "Report Page" to "About Page" However, it can't Go Back from the Report Page to the Home Page. The url won't switch.

import {
  BrowserRouter as Router,
  Route,
  Routes,
  useNavigate
} from "react-router-dom";
import ReactDOM from "react-dom";

const Home = () => {
  const navigate = useNavigate();
  return (
    <div>
      <h1>Home Page</h1>
      <button onClick={() => navigate("/about")}>To about</button>
    </div>
  );
};

const About = () => {
  const navigate = useNavigate();
  return (
    <div>
      <div>About Page</div>
      <button onClick={() => navigate("/report")}>Go to Report</button>
      <button onClick={() => navigate(-1)}>Go back</button>
    </div>
  );
};

const Report = () => {
  const navigate = useNavigate();
  return (
    <div>
      <div>Report Page</div>
      <button onClick={() => navigate(-1)}>Go back</button>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(
  <Router>
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="about" element={<About />} />
      <Route path="report" element={<Report />} />
    </Routes>
  </Router>,
  rootElement
);

https://codesandbox.io/s/reactrouterdomv61-6xq51

2 Answers
import React, { FunctionComponent } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';


const PageEx: FunctionComponent = () => {
  const navigate = useNavigate();
  const { key: keyLocation } = useLocation();

  const handleGoBack: VoidFunction = () => {
    const isInitialLocation: boolean = keyLocation === 'default'; // <-- This value is always "default" on the initial location.
    const to: any = isInitialLocation ? '/' : -1;
    navigate(to);
  };

  return (
    <>
      <button onClick={handleGoBack}>Go back or if initial location go home</button>
    </>
  );
};

This works for me:

onClick={() => navigateBack((-1), { replace: true })}
Related