Hamza Ahmad
Hamza Ahmad

Reputation: 1

Call multiple functions with onClick event in React.js

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",
  },

Upvotes: 0

Views: 96

Answers (1)

Quentin
Quentin

Reputation: 943569

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).

Upvotes: 1

Related Questions