Responsive Advertisement

How to save the previous location in React Router after Redirect?

 


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:

import React, { useEffect, useRef } from 'react';
import { useHistory, useLocation, Redirect } from 'react-router-dom';

const MyComponent = () => {
  const location = useLocation();
  const history = useHistory();
  const prevLocationRef = useRef(null);

  useEffect(() => {
    prevLocationRef.current = location;
  }, [location]);

  const handleClick = () => {
    // Save the current location before redirecting
    prevLocationRef.current = location;
    history.push('/my-other-page');
  };

  if (/* some condition that requires a redirect */) {
    // Redirect to a different page
    return <Redirect to="/my-other-page" />;
  }

  return (
    <div>
      <p>This is my component</p>
      <button onClick={handleClick}>Go to another page</button>
    </div>
  );
};

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.

Post a Comment

0 Comments