Home > Mobile >  Should a <Route> be wrapped in a <Routes>?
Should a <Route> be wrapped in a <Routes>?

Time:12-03

After my React code compiles, I'm getting an error that says the following:

Error: A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.

Here is my code:

import { Route } from "react-router-dom";
import AllMeetupsPage from "./pages/AllMeetups";
import NewMeetupsPage from "./pages/NewMeetups";
import FavoritesPage from "./pages/Favorites";

function App() {
 

  return (
    <div>
      <Route path="/">
        <AllMeetupsPage />
      </Route>
      <Route path="/new-meetups">
        <NewMeetupsPage />
      </Route>
      <Route path="/favorites">
        <FavoritesPage />
      </Route>
    </div>
  );
}

export default App;

What am I doing wrong?

CodePudding user response:

Simply follow the instructions in the error message and wrap your routes with <Routes>:

<Routes>
  <Route path="/">
    <AllMeetupsPage />
  </Route>
  <Route path="/new-meetups">
    <NewMeetupsPage />
  </Route>
  <Route path="/favorites">
    <FavoritesPage />
  </Route>
</Routes>

CodePudding user response:

You'll need to also wrap the <Routes> component in a router, <BrowserRouter> is the router referenced in the installation guide.

React Router v6 installation guide:
https://reactrouter.com/docs/en/v6/getting-started/overview


import { BrowserRouter, Routes, Route } from "react-router-dom";
import AllMeetupsPage from "./pages/AllMeetups";
import NewMeetupsPage from "./pages/NewMeetups";
import FavoritesPage from "./pages/Favorites";

function App() {
 

  return (
    <div>
      <BrowserRouter>
        <Routes>
          <Route path="/">
            <AllMeetupsPage />
          </Route>
          <Route path="/new-meetups">
            <NewMeetupsPage />
          </Route>
          <Route path="/favorites">
            <FavoritesPage />
          </Route>
        </Routes>
      </BrowserRouter>
    </div>
  );
}

export default App;
  • Related