Home > Back-end >  How to keep the active menu selected in React?
How to keep the active menu selected in React?

Time:08-27

I have some menu items in a component and some styling added to the selected menu item. When I refresh the page, I want the selected menu to persist and not the initial state.



import ClaimData from "./Data";


const Services = () => {
  const [tabIndex, setTabIndex] = useState(1);
  const [selected, setSelected] = useState(1);

 

  return (
    <section >
      <h3>
        Menu
      </h3>

      <div>
        {ClaimData.map((item, index) => {
          return (
            <div
              key={index}
              style={
                selected === item.tabNum
                  ? {
                      borderBottom: "3px solid green",
                      backgroundColor: "#E8E8E8",
                    }
                  : null
              }
              onClick={() => setSelected(item.tabNum)}
            >
              <p
                onClick={() => setTabIndex(item.tabNum)}
                style={{ color: item.color }}
                
              >
                <item.icon />
                <span>{item.title}</span>
              </p>
            </div>
          );
        })}
      </div>
    
      <div>
        {tabIndex === 1 && <MenuOneComponent />}
        {tabIndex === 2 && <MenuTwoComponent />}
        {tabIndex === 3 && <MenuThreeComponent />}
      
      </div>
    </section>
  );
};

export default Services;

I have removed some codes for brevity. I would appreciate any help

CodePudding user response:

To presist state on refresh you need to store the state outside of react. Easiest would propbably be to use localStorage or sessionStorage. But it is of course possible to save it in a database/redis.

CodePudding user response:

One way is to use url to determine which menu to highlight.

  • Related