Reputation: 136
I'm trying to reuse my MainSection component for two different purposes (single story and all stories). To effect this, I want to pass in a property, home, in the Routes that go to those renderings of that component. Home is true or false, and I want to render the MainSection component based on that boolean. However, I home keeps being undefined when MainSection gets rendered. The link and route are updating the URL, but not rendering with the props I want. Am I doing something wrong?
Here are my routes:
function Routes(){
return(
<Switch>
<Route path="/" element={<MainSection home={true} />} />
<Route path="/story" element={ <MainSection home={false} />} />
</Switch>
)
}
and here is the code for my MainSection component:
function MainSection({ home }){
console.log(home)
return(
<div className="main-section">
<BigPicture home={ home }/>
<Quotes home={ home }/>
</div>
)
}
The console log keeps returning undefined.
Thanks!
Upvotes: 6
Views: 24418
Reputation: 202751
Since in the question title you state you are using react-router-dom
version 6 I'll answer against that. V6 doesn't export a Switch
component, it was replaced by a Routes
component. Swap the Switch
for the Routes
component and rename your Routes
component to something else to avoid the name collision.
function MainRoutes(){
return(
<Routes>
<Route path="/" element={<MainSection home />} />
<Route path="/story" element={<MainSection />} />
</Routes>
)
}
From here the home
prop should either be treated as truthy/falsey. You can double-bang it to coerce it to a strict boolean value. Passing home
through to children components should also work without issue.
function MainSection({ home }) {
React.useEffect(() => {
console.log(!!home);
}, [home]);
return(
<div className="main-section">
<BigPicture home={home} />
<Quotes home={home} />
</div>
)
}
Upvotes: 11