0

I want to redirect to last 2nd route in my react app when user go backs from a particular route but I'm not able to find a solution. Anybody who can help??

I want this when user clicks on back button but not when component unmount.

Spyder
  • 66
  • 4

1 Answers1

0

You can achieve this using the useHistory hook.

First, import it:

import { useHistory } from "react-router-dom";

Second, call it and save its return value in a constant:

const history = useHistory();

Then call the goBack() method to go once back, or the go(n) to go back n times in the stack history:

history.go(-2);

You can read more in the official docs: https://v5.reactrouter.com/web/api/history


If you are using version 6, use the useNavigate hook instead:

import { useNavigate } from "react-router-dom";
// ...
const navigate = useNavigate();
// ...
navigate(-2);

You can read more here: https://reactrouter.com/docs/en/v6/hooks/use-navigate

Tarek Hammami
  • 840
  • 9
  • 12