Tony
Tony

Reputation: 77

How to keep the active menu selected in React?

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

Upvotes: 0

Views: 409

Answers (2)

Rojen
Rojen

Reputation: 346

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

Upvotes: 0

Erik
Erik

Reputation: 485

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.

Upvotes: 2

Related Questions