0

The only problem I am facing is, either one of them dont work when put together. Both work fine independently. When put together, I can see the routes changing but the active Item doesn't switch.

 {SidebarData.map((item, index)=>{
      return(
        <div className={selected===index?'menuItem active': 'menuItem'}
        key={index}
        onClick={()=>{setSelected(index); window.location.pathname= item.link;    }}
       
        >
          <item.icon/>
          <span>
            {item.heading}
          </span>
        </div>
      )
    })}


export const SidebarData = [
  {
    icon: UilEstate,
    heading: "Dashboard",
    link: "/Dashboard",
  },
  {
    icon: UilLaptop ,
    heading: "Exams",
    link: "/Exams",
  },
  {
    icon: UilFileCheck ,
    heading: "Results",
    link: "/Result",
  },
1
  • Div elements are not designed to be interactive. Screen readers won't announce them as clickable. Non-pointing device users can't tab to them. Search engines may not find them. Use a link instead. Commented May 21, 2022 at 20:56

1 Answer 1

1

Assigning a new value to window.location.pathname will cause the browser to navigate to the new URL and load it as a new page.

If that URL also serves up your React application, then it will be run from scratch and all existing state (including the result of running setSelected(index);) will be lost.

Use Next.js or Gatsby to handle routing with static page generation or server-side rendering. Use BrowserRouter for routing with your own fallback code or HashRouter for a pure single page application with no server-side fallback.

These all have methods for passing state data through the link, so you can avoid using setState as well.

(You could also use BrowserRouter and serve up the same content-less bootstrap HTML document for every URL, but that isn't an efficient approach).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.