React js: Error: useLocation() may be used only in the context of a <Router> component

Solution 1:

I had the same issue. My issue is because of the following reason. I had a Header component which consists of NavLink which is a router component. I placed this Header component inside the App component. My App component was like this:

function App() {
  return(
      <Header/>
      <Router>
        <Routes>
          <Route path="/" element={<Homepage/>}/>
          <Route path="/shop" element={<Shop/>}/>
          <Route path="/signin" element={<Signin/>}/>
        </Routes>
      </Router>
  )
}

In the above App component, I have placed Header component outside of Router. Since in the Header component I have used NavLink which is a Router component caused this error. Then I moved Header component into the Router component then it worked fine. Finally my code looked like this:

function App() {
  return(
      <Router>
        <Header/>
        <Routes>
          <Route path="/" element={<Homepage/>}/>
          <Route path="/shop" element={<Shop/>}/>
          <Route path="/signin" element={<Signin/>}/>
        </Routes>
      </Router>
  )
}

Solution 2:

Make sure that your App component in index.js is wrapped with BrowserRouter like this

const app = (
  <Provider store={store}>
      <BrowserRouter>
          <App />
      </BrowserRouter>
  </Provider>
);