Go Back button is not working when added a query param in ReactJs

Viewed 4238

Let me introduce what I am doing which is causing the issue. I have 3 routes in my React web application:

  1. "/" for home page.
  2. "/page2" for page2.
  3. "/page3" for page3.

Now what I am doing as soon as when I go on route "/page2", I push a query param in the URL to render the default tab in page2 making the URL as "/page2?activeTab=tabId". So in a brief, when I will try to go to "/page2" it will always make the URL as "/page2?activeTab=tabId".

Now the issue is when I land on Page2 for the first time and try to press back button on browser. I again and again re-renders page2. The reason is: Suppose I am on page2 for the first time and the URL will be as "/page2?activeTab=tabId". Now when I press back button, the browser removes the query param and renders the URL "/page2". So whenever the URL renders my code again turns it to "/page2?activeTab=tabId". Because of this I can't go back and stuck at the second page only.

I want help in this. How to eliminate or avoid this issue?

2 Answers

You can check the location search params, and if empty compute a new path URL and replace the current location in history.

  1. Check location search query
  2. If search query empty, construct new path URL with query string
  3. Redirect (replace) the current page so back button works

Using react-router-dom's useHistory and useLocation react hooks

const MyComponent = () => {
  const { replace } = useHistory();
  const { pathname, search } = useLocation();

  useEffect(() => {
    const tabId = <compute tab id>;
    const newPath = `${pathname}?activeTab=${tabId}`;
    if (!search) replace(newPath);
  }, [pathname, replace, search]);

  return (
    ...
  );
};

If not able to use the react hooks of react-router-dom, then you can decorate your component with the withRouter Higher Order Component and access the same values from the injected props.

const MyComponent = ({ history, location }) => {
  const { replace } = history;
  const { pathname, search } = location;

  useEffect(() => {
    const tabId = <compute tab id>;
    const newPath = `${pathname}?activeTab=${tabId}`;
    if (!search) replace(newPath);
  }, [pathname, replace, search]);

  return (
    ...
  );
};

export withRouter(MyComponent);

Edit go-back-button-is-not-working-when-added-a-query-param-in-reactjs

Using Redirect and Route you can solve this issue. Maybe following code snippet can help you.

  <Switch>
     <Redirect from='/page2' to='/page2?activeTab=tabId' />
     <Route path="/page2?activeTab=tabId" >
       <Page2 />
     </Route>
     //....
  </Switch>

Sandbox working example

Related