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

ID : 274555

viewed : 38

Tags : javascriptreactjsreact-router-domjavascript





Top 5 Answer for javascript - React js: Error: useLocation() may be used only in the context of a <Router> component

vote vote

97

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>   ) } 
vote vote

82

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

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

70

Already wrapped in Router?

if your component is already wrapped in a Router. Make sure you are importing useLocation from react-router-dom instead of react-router. this worked for me.

vote vote

64

In case you run into this problem when running a test, don't forget to wrap your import of App in Router as well. My crude example is below.

import { render, screen } from '@testing-library/react'; import { BrowserRouter } from 'react-router-dom';  import { App } from '../App';  test('renders Box', () => {   render(     <BrowserRouter>       <App />     </BrowserRouter>   );   const boxElement = screen.getByLabelText('box-outline');   expect(boxElement).toBeInTheDocument(); }); 
vote vote

54

I had the same error coming up from inside a test. The component I was testing contained a NavLink component, and I wasn't rendering a Router in the test. This error disappeared after wrapping my component in question with BrowserRouter.

Top 3 video Explaining javascript - React js: Error: useLocation() may be used only in the context of a <Router> component







Related QUESTION?