'React Router v6 error: All component children of <Routes> must be a <Route> or <React.Fragment>

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

}


Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Asad Haroon