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.
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'}
/>
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}
/>;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With