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

You can check location.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}
/>;

For V6 and newer:

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

<Button
  onClick={() => {
    if (location.key !== 'default') {
      history.goBack();
    }
  }}
  disabled={location.key === 'default'}
/>;

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)