Skip to content
Advertisement

React Router v6 error: All component children of must be a or

The following React routes code probably works in React Router v5, but gives the following error in React Router v6

Error: [Player] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

Is it possible to update the Routes/Route code so that it works in React Router v6?

function App() {
  // Some stuff here...

  const { players, offlinePlayers } = usePlayers();


  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
        <BrowserRouter>

            <Routes>
                <Route path="/" element={<Home />} />

                <Route path="/players">
                {players.map((player) => {
                    return (
                    <Route exact key={player.name} path={`/players/${player.name}`}>
                        <Player player={player} />
                    </Route>
                    );
                })}
                </Route>
            </Routes>  

        </BrowserRouter>
    </ThemeProvider>
  )

}

Advertisement

Answer

The Player component should be rendered by a Route component on the element prop, not as a child of the Route.

<BrowserRouter>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/players">
      {players.map((player) => (
        <Route
          key={player.name}
          path={`/players/${player.name}`}
          element={<Player player={player} />}
        />
      ))}
    </Route>
  </Routes> 
</BrowserRouter>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement