Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if react-router can go back to display back button in react app

Tags:

There seems to be no API way to detect if you can go back from the current page in an app. One can check the history length, but that includes the forward and backward stack.

I want to display the back button only when the user actually can go back.

like image 934
philk Avatar asked May 23 '16 07:05

philk


2 Answers

You can do it by checking history.action if its value is POP, then there is no route to go back. That's the only way I found.

<Button
  onClick={() => {
    if (history.action !== 'POP') history.goBack();
  }}
  disabled={history.action === 'POP'}
/>
like image 114
Haseeb Anwar Avatar answered Sep 29 '22 19:09

Haseeb Anwar


You can check loction.key if you have a location key that means you routed in-app. But if you don't that means you come from outside of the app or you just open the app in a new tab etc.

import { useHistory, useLocation } from "react-router-dom";
const HISTORY = useHistory();
const LOCATION = useLocation();

<Button
  onClick={() => {
    if (LOCATION.key) {
      HISTORY.goBack();
    }
  }}
  disabled={!LOCATION.key}
/>;
like image 45
Tugay Yaldız Avatar answered Sep 29 '22 19:09

Tugay Yaldız