'React-router-dom how to use the goBack function without usingHistory

How can I simulate pressing the "back" button in the browser from the code?

const history = useHistory()
history.goBack()

I know I can do this as well, but as I understood in the new versions of react-router-dom useHistory was changed to useNavigate, which has no goBack() function. How can I go back to the last page without rolling back react-router-dom?



Solution 1:[1]

...in the new versions of react-router-dom useHistory was changed to useNavigate, which has no goBack() function.

This isn't entirely accurate. In react-router-dom@6 the useHistory hook was replaced by the useNavigate hook. The useNavigate hook returns a navigate function instead of a history object with navigation methods.

useNavigate

declare function useNavigate(): NavigateFunction;

interface NavigateFunction {
  (
    to: To,
    options?: { replace?: boolean; state?: any }
  ): void;
  (delta: number): void;
}

Further

The navigate function has two signatures:

  • Either pass a To value (same type as ) with an optional second { replace, state } arg or
  • Pass the delta you want to go in the history stack. For example, navigate(-1) is equivalent to hitting the back button.

You want to use the delta argument. If you recall from RRDv4/5 that history.goBack() is equivalent to history.go(-1).

v4 history

// Go back to the previous history entry. The following
// two lines are synonymous.
history.go(-1);
history.goBack();

Solution

How can I go back to the last page without rolling back react-router-dom?

In react-router-dom@6 to issue a back navigation, i.e. POP:

const navigate = useNavigate();

navigate(-1);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Drew Reese