'<Route component> and <Route children> in the same route
Warning: You should not use Route component and Route children in the same route; Route component will be ignored
import { BrowserRouter, Route, Switch } from "react-router-dom"
import { useState } from "react";
import SideBar from "./SideBar";
import Playing from "./Playing";
import "./App.css";
import AllSong from "./Components/AllSong";
import Favourites from "./Components/Favourites";
function App() {
const [sidebar, setSidebar] = useState(false);
return (
<BrowserRouter>
<div className="box image photo">
<SideBar sidebar={sidebar}/>
<Switch>
<Route path="/" exact component={Playing}>
<Playing sidebar={sidebar} setSidebar={(bool) => setSidebar(bool)}/>
</Route>
<Route path="/AllSong" component={AllSong}/>
<Route path="/Favourites" component={Favourites}/>
</Switch>
</div>
</BrowserRouter>
);
}
export default App;
Can someone explain why is the warning coming and also help to improve the code. (I'm new to react)
I tried using the v6 for react-router and react-router-dom b ut it showed number of errors so i degraded again and used switch again
Thanks You.
Solution 1:[1]
This is happening because you have <Route path="/" ...> & within that you have <Playing... so this confuses the Router & it doesn't know whether to render the parent <Route ... or the child <Playing... hence the error.
Solution 2:[2]
Like the warning says, you can't specify both a route component and wrap children components.
From the docs:
Warning:
<Route children>takes precedence over both<Route component>and<Route render>so don’t use more than one in the same<Route>.
The issue is specifically with:
<Route path="/" exact component={Playing}>
<Playing sidebar={sidebar} setSidebar={(bool) => setSidebar(bool)}/>
</Route>
You are rendering Playing in both places. Since it seems like you want to pass additional props into Playing then I suggest using the render prop so Playing can also still receive route props, i.e. history, location, and match props.
<Route
path="/"
exact
render={props => (
<Playing
{...props}
sidebar={sidebar}
setSidebar={(bool) => setSidebar(bool)}
/>
)}
/>
See Route render methods for further clarification on rendering routed content by a Route component.
Solution 3:[3]
it is specifically these lines:
<Route path="/" exact component={Playing}>
<Playing sidebar={sidebar} setSidebar={(bool) => setSidebar(bool)}/>
</Route>
you're setting both the component
component={Playing}
and the children
<Playing sidebar={sidebar} setSidebar={(bool) => setSidebar(bool)}/>
React will only render one of them so one of them has to be ignored, in this case the component.
If you remove one of them the warning will disappear.
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 | |
| Solution 2 | |
| Solution 3 |
