Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

402
Views
Error when put <BrowserRouter> and useRoutes(routes) in A function component in React

I'm using react-router-dom in my react app. When I use:

function App() {
    return (
        <BrowserRouter>{ useRoutes(routes) }</BrowserRouter>
    );
}

And I got error message: Uncaught Error: useRoutes() may be used only in the context of a <Router> component.

I've searched how to fix it and change my code's structure to:

function App() {
    return (
        <BrowserRouter><Foo/></BrowserRouter>
    );
}
function Foo() { 
    return useRoutes(routes)
}

The code works properly.

As a starter, I can't tell the exact difference between the two snippet above, could someone please help?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Uncaught Error: useRoutes() may be used only in the context of a <Router> component.

All this message is saying is that there needs to be a routing context provider higher in the ReactTree than this App component that is trying to consume it when using the useRoutes hook.

A clearer bad example:

function App() {
  const routes = useRoutes(routes); // <-- (2) but needed here!
  return (
    <BrowserRouter> // <-- (1) context provided here
      {routes}
    </BrowserRouter>
  );
}

Here you can clearly see that the router is below the App component and there is no routing context provided to App.

This is why the second snippet works, it's providing the routing context higher than the component consuming it.

function App() {
  return (
    <BrowserRouter> // <-- (1) context provided here
      <Foo/> // <-- (2) context consumed here
    </BrowserRouter>
  );
}

function Foo() { 
  return useRoutes(routes);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!