简体   繁体   中英

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

I have installed react-router-dom V6-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;

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

So an example looks 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.

You should have a <BrowserRouter> (or any ofthe 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'),
);

Mention below code in index.js

import { BrowserRouter as Router } from "react-router-dom";

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"),
);

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>
</>
  );
}

If you want to keep everything in your App-component

import { BrowserRouter, useRoutes } from "react-router-dom"; // v6 beta

import Home from './pages/Home';

const App = () => {
  const Routes = () => useRoutes([{ path: "/", element: <Home /> }]);

  return (
    <BrowserRouter>
      <Routes />
    </BrowserRouter>
  );
};

export default App;

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.

Ie, 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';
> 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;

Try

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

and then wrap it like this in App.js

<BrowserRouter> 
    <Routes />
</BrowserRouter>

It worked for me

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>
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM