BraulioPortela
BraulioPortela

Reputation: 329

How to change the state when going to previous or next page with React?

I have a state to keep track when a Sub Menu is opened, and toggle it when another Menu Item is clicked. It goes like this:

    const [open, setOpen] = useState();
    const toggle = (id) => setOpen(id);

    onClick={() => toggle(item.navId)}

So, every time I click on a Menu Item, it closes/opens the Sub Menu. But when I click the browser´s buttons to go to the previous page or the next page, the current opened Sub Menu remains opened and it doesn´t open the Sub Menu that was redirected nor close the current opened Sub Menu. What could I use, just like onClick to change the state, when I navigate through the pages with the previous/next buttons in the browser? Thanks!

Upvotes: 1

Views: 5895

Answers (2)

Mainly Karma
Mainly Karma

Reputation: 477

I found a similar stack post here and I believe someone's answer might help you with a little modification

import React from "react";
import useHistory from "react-router-dom";
import { SubMenu, OtherComponent } from './'; // import your actual components here

export default function YourComponent() {

  const [open, setOpen] = React.useState(false); // toggle submenu
  const [locationKeys, setLocationKeys] = React.useState([]);
  const history = useHistory();

  React.useEffect(() => {
    return history.listen((location) => {
      if (history.action === "PUSH") {
        if (location.key) setLocationKeys([location.key]);
      }

      if (history.action === "POP") {
        if (locationKeys[1] === location.key) {
          setLocationKeys(([_, ...keys]) => keys);

          // Handle forward event
          console.log("forward button");
          setOpen(!open); // toggle submenu
        } else {
          setLocationKeys((keys) => [location.key, ...keys]);

          // Handle back event
          console.log("back button");
          setOpen(!open); // toggle submenu
        }
      }
    });
  }, [locationKeys, history]);

  return (
    <div>
      {open ?? <SubMenu/>}
      // or
      {open ? <SubMenu/> : <OtherComponent/>}
    </div>
  );
}

Upvotes: 1

WebbH
WebbH

Reputation: 2422

If you are using react router, you could use the useLocation hook and useEffect to handle closing the menu on route change

const {pathname} = useLocation();
useEffect(()=>{
  setOpen(//whatever here)
},[pathname])

Upvotes: 1

Related Questions