Home > Mobile >  Error: A <Route> is only ever to be used as the child of <Routes> element
Error: A <Route> is only ever to be used as the child of <Routes> element

Time:11-04

Trying to use routing for the first time, and followed the exact instructions from Udemy:

App.js:

import { Route } from "react-router-dom";
import Welcome from "./Pages/Welcome";
import Game from "./Pages/Game";
import Leaderboard from "./Pages/Leaderboard";

function App() {
    return (
        <div>
            <Route path = "/welcome">
                <Welcome />
            </Route>
            <Route path = "/game">
                <Game />
            </Route>
            <Route path = "/leaderboard">
                <Leaderboard />
            </Route>
        </div>
    );
}

export default App;

index.js:

import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from "./App";

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

I get the following error:

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

Where have I gone wrong??

CodePudding user response:

Try to wrap your routes by Routes:

import { Route, Routes } from "react-router-dom";
import Welcome from "./Pages/Welcome";
import Game from "./Pages/Game";
import Leaderboard from "./Pages/Leaderboard";

function App() {
    return (
        <div>
          <Routes>
            <Route path = "/welcome">
                <Welcome />
            </Route>
            <Route path = "/game">
                <Game />
            </Route>
            <Route path = "/leaderboard">
                <Leaderboard />
            </Route>
           </Routes>
        </div>
    );
}

export default App;

CodePudding user response:

There was a fairly decent change between versions 5 and 6 of react-router-dom. It appears that the Udemy course/tutorial is using version 5 where all you needed was a Router to provide a routing context and Route components just needed to be rendered within this context. In version 6, however, the Route components now need to be rendered within a Routes component (which is an upgrade from the v5 Switch component).

Introducing Routes

One of the most exciting changes in v6 is the powerful new <Routes> element. This is a pretty significant upgrade from v5's <Switch> element with some important new features including relative routing and linking, automatic route ranking, and nested routes and layouts.

The error message is pretty clear, wrap your Route components in a Routes component.

function App() {
  return (
    <div>
      <Routes>
        <Route path="/welcome">
          <Welcome />
        </Route>
        <Route path="/game">
          <Game />
        </Route>
        <Route path="/leaderboard">
          <Leaderboard />
        </Route>
      </Routes>
    </div>
  );
}
  • Related