'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?
Solution 1:[1]
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);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Drew Reese |
