Reputation: 3409
I need to route between 2 paths,
I installed npm install react-router
(react-router: 6.2.1 and react-router-dom: 5.2.0).
I get a error saying in the webpage Error: useRoutes() may be used only in the context of a <Router> component.
which eventually meant I din't warp my index.js file with BrowserRouter but I did.
Code: index.js
import {BrowserRouter as Router} from "react-router-dom";
ReactDOM.render(
<React.StrictMode>
<Router>
<App />
</Router>
</React.StrictMode>,
document.getElementById("root")
);
app.js
function App() {
return (
<>
<Routes>
<Route path ="/" element={<Main />} />
<Route path ="gigs" element={<Gigs />} />
</Routes>
</>
);
}
Upvotes: 5
Views: 16323
Reputation: 518
You can try to wrapp your component in this way instead
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { BrowserRouter } from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
Upvotes: 1
Reputation: 202801
The issue here is that you are specifying two different versions. The router you are using is from v5, but the Routes
and Route
components are expecting a v6 router providing a specific v6 context.
If you are using react-router-dom
version 6 components then you need to use version 6 of react-router-dom
. You can remove react-router
since react-router-dom
re-exports these components.
From the project directory run the commands:
Unintall react-router
and react-router-dom
npm uninstall -s react-router react-router-dom
Install react-router-dom
version 6
npm install -s react-router-dom
Upvotes: 3
Reputation: 56
I'm pretty sure you don't need to wrap your Routes
component in a React Fragment. It also seems that it might cause problems with react router as mentionned here.
Also I would either add a /
in front of gigs
, or nest the gigs
route in the /
route.
Upvotes: 0
Reputation: 3560
The issue here the mistake between react router version and which version you target to use...
you need to determine which version you like to use, if v6, then you need to follow the v6 rule, if v5 then you need to follow v5...
for example:
"react-router": "6.2.1",
"react-router-dom": "6.2.1"
Now for the code diff: in V6:
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="about" element={<About />} />
<Route path="dashboard" element={<Dashboard />} />
{/* Using path="*"" means "match anything", so this route
acts like a catch-all for URLs that we don't have explicit
routes for. */}
<Route path="*" element={<NoMatch />} />
</Route>
</Routes>
in V5:
<Router>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/dashboard">
<Dashboard />
</Route>
</Switch>
</div>
</Router>
Upvotes: 2