简体   繁体   中英

React router error "useRoutes() may be used only in the contect of a <Router> component."

So, I was making this website when I saw these BIG red errors in the console ( I know a nightmare:( ) The error said this:

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

And I didn't even use a "useRoutes" hook. Anyways here's my code:

import Links from "./components/Links"
import Addition from "./pages/Addition"
import "./styles/App.css"
import { BrowserRouter as Router, Switch, Route, Routes } from 'react-router-dom';

function App() {
  return (
    <div>
      <h1>Chose your operation:</h1>
      <div className="cards">
        <Routes>
          <Route path="/addition" element={Addition} />
        </Routes>
      </div>
    </div>
  )
}

export default App;

The Routes component uses the useRoutes . Routes needs to be rendered within a routing context provided by a router component.

Additionally the Addition ( sorry, no pun intended ) needs to be passed to the element prop as JSX . This was one of the breaking changes in the Route component API from v5 to v6.

Example:

import Links from "./components/Links"
import Addition from "./pages/Addition"
import "./styles/App.css"
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

function App() {
  return (
    <Router> // <-- render app into Router component
      <div>
        <h1>Chose your operation:</h1>
        <div className="cards">
          <Routes>
            <Route
              path="/addition"
              element={<Addition />} // <-- passed as JSX
            />
          </Routes>
        </div>
      </div>
    </Router>
  )
}

编辑 react-router-error-useroutes-may-be-used-only-in-the-contect-of-a-router-co

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