React-router check if can go back

Viewed 1836

Is there any way to know if there are any pages to go back to?

I have tried checking the value of history.length, assuming that any value greater than 1 means that we can still go back (including browser start pages). However, this solution doesn't cover cases where user has advanced several pages forward:

  • Open the first page (history.length === 1)
  • Go to the next page (history.length === 2)
  • Go back one page (history.length is still 2)

I have also tried setting a timeout to check if there are any changes on the url & query params after a few millisecond (which work on most cases, but not all), and I was wondering if there is any better way to handle this.

1 Answers

Solution that works for BroswerHistory but uses the history.entries member which isn't officially documented:

function isHistoryRoot(history) {
  if (!history) return false;

  if (history.length === 1) return true;

  return history.location.pathname === history.entries[0].pathname;
}

const history = useHistory(); // react-router hook
const isRoot = isHistoryRoot(history);
Related