Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

403
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda