How to save the previous location in React Router after Redirect?
In React Router, you can save the previous location after a redirect by using the useRef hook and storing the previous location in a mutable reference. Here's an example of how you can do this:
In this example, we're using the useRef hook to create a mutable reference prevLocationRef that will store the previous location. We're then using the useEffect hook to update the prevLocationRef reference whenever the location prop changes. When the user clicks on the button, we save the current location in the prevLocationRef reference before redirecting to another page using the history.push method. If there's some condition that requires a redirect, we're returning a Redirect component that will redirect the user to a different page. Otherwise, we're rendering the component as usual. Now, after the user has been redirected to another page and then navigates back to this component, the prevLocationRef.current value will contain the previous location, which you can use as needed.
0 Comments