Home > Mobile >  React Router v6 error: All component children of <Routes> must be a <Route> or <React
React Router v6 error: All component children of <Routes> must be a <Route> or <React

Time:03-03

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

}

CodePudding user response:

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>

CodePudding user response:

You should map Routes in their parent route. Like:

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

But if you want to render dynamic player then dont use the above code for that purpose because its not best approach if you are using dynamic player.name. In your code you are creating each route for every player. So, use the following code:

<Route path="/players">
   <Route exact path={":playerName"} element={<Player/>} />
</Route>

And in Player component, extract playerName from params like:

let { playerName } = useParams();
  • Related