React Router V6 - Error: useRoutes() may be used only in the context of a <Router> component
Asked Answered
A

11

112

I have installed react-router-domV6-beta. By following the example from a website I am able to use the new option useRoutes I have setup page routes and returning them in the App.js file.

After saving I am getting the following error:

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

I am wondering If I am missing something here? I have created the pages inside the src/pages folder.

My code:

import { BrowserRouter, Link, Outlet, useRoutes } from 'react-router-dom';

// Pages
import Home from './pages/Home';
import About from './pages/About';
import Services from './pages/Services';
import Gallery from './pages/Gallery';
import Prices from './pages/Prices';
import Contact from './pages/Contact';

const App = () => {
    const routes = useRoutes([
        { path: '/', element: <Home /> },
        { path: 'o-nama', element: <About /> },
        { path: 'usluge', element: <Services /> },
        { path: 'galerija', element: <Gallery /> },
        { path: 'cjenovnik', element: <Prices /> },
        { path: 'kontakt', element: <Contact /> }
    ]);

    return routes;
};

export default App;
Abigailabigale answered 23/12, 2020 at 14:26 Comment(0)
P
174

You should have a <BrowserRouter> (or any of the provided routers) higher up in the tree. The reason for this is that the <BrowserRouter> provides a history context which is needed at the time the routes are created using useRoutes(). Note that higher up means that it can't be in the <App> itself, but at least in the component that renders it.

Here's what your entry point could look like:

import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';


ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root'),
);

Precipitancy answered 1/11, 2021 at 11:5 Comment(2)
This appears to be untrue. github.com/remix-run/react-router/blob/dev/examples/basic/src/…Alfred
Look at main file github.com/remix-run/react-router/blob/dev/examples/basic/src/…Reverend
L
101

I think the problem is that you still need to wrap routes (Routes / useRoutes) inside a Router element.

So an example would look something like this:

import React from "react";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  useRoutes,
} from "react-router-dom";

const Component1 = () => {
  return <h1>Component 1</h1>;
};

const Component2 = () => {
  return <h1>Component 2</h1>;
};

const App = () => {
  let routes = useRoutes([
    { path: "/", element: <Component1 /> },
    { path: "component2", element: <Component2 /> },
    // ...
  ]);
  return routes;
};

const AppWrapper = () => {
  return (
    <Router>
      <App />
    </Router>
  );
};

export default AppWrapper;

Refactor according to your needs.

Lordsandladies answered 23/12, 2020 at 16:4 Comment(1)
The BrowserRouter as Router, was missing on my side.Lakes
C
16

its means in Your index js Or App JS wrap with BrowserRouter like this

import { BrowserRouter } from 'react-router-dom';

ReactDOM.render(
    <React.StrictMode>
        <Provider store={store}>
            <BrowserRouter>  // Like This here I am using
                <App />
           </BrowserRouter>
       </Provider>
    </React.StrictMode>,
    document.getElementById("root"),
);

Chartism answered 2/2, 2021 at 20:24 Comment(0)
M
12

Mention below code in index.js

import { BrowserRouter as Router } from "react-router-dom";
Moray answered 7/4, 2021 at 10:17 Comment(0)
M
8

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>
</>
  );
}
Mcclenon answered 16/3, 2022 at 14:28 Comment(0)
K
6

Try to add your routes in index.js not in App.js. Your App.js is called from index.js. In the index.js your external page is called like this

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Navbar />} />
      </Routes>
    </BrowserRouter>
  </React.StrictMode>
);
Kitchens answered 17/11, 2022 at 15:39 Comment(0)
T
4

Just want to report on a similar issue -- as of writing (v6.2.1), it seems you actually encounter this error as well if you are importing from react-router instead of react-router-dom. A costly typo on my part.

I.e., make sure you are importing Routes and Route from react-router-dom and NOT react-router

// This is deceptively valid as the components exist, but is not the intended usage
import { Routes, Route } from 'react-router';

// This works and is the intended usage
import { Routes, Route } from 'react-router-dom';
Tate answered 11/1, 2022 at 0:4 Comment(2)
As funny as it seems this is actually a valid solution, my app crashes because of this simple mistake. ThanksMettah
This. My project worked fine through v6.3.0 of React Router, but as soon as I upgraded to 6.4.x, kaboom. Thanks for the fix on a very sticky problem!Apologize
D
1
> Following codes works since react-router-dom syntax changed because of React 18.

  import logo from './logo.svg';
    import './App.css';
    import Header from './components/Header';
    import Login from './components/Login';
    import {
      BrowserRouter as Router,
      Routes,
      Route,
      useRoutes,
    } from 'react-router-dom';
    import Signup from './components/Signup';
    
    function AppRoutes() {
      const routes = useRoutes(
        [
          {path:'/',element:<Login/>},
          {path:'/signup',element:<Signup/>}
        ]
      )
      return routes;
    }
    function App(){
      return (
        <Router>
          <Header/>
          <AppRoutes />
        </Router>
      )
    }
    
    export default App;
Dichromatic answered 29/3, 2022 at 20:46 Comment(0)
R
0

Try

const Routes = () => useRoutes([]) 

and then wrap it like this in App.js

<BrowserRouter> 
    <Routes />
</BrowserRouter>

It worked for me

Rumormonger answered 15/11, 2022 at 8:18 Comment(0)
R
0

I got this error because I had two different versions of react-router-dom being bundled.

If you're using npm/yarn workspaces, check that there is only one installed version of react-router-dom in the top-level node_modules folder

Radii answered 6/2, 2023 at 4:5 Comment(0)
O
0

If you are getting this error, then you forgot to wrap your <Route> tags with a <BrowserRouter> tag in App.js. By the way you can also wrap around your entire App Component in index.js instead of wrapping it around your Tags in App.js.

Oisin answered 19/12, 2023 at 10:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.