Reputation: 927
I have two components FirstLayout
and SecondLayout
that require Header
component for displaying the completed page.
At this moment I have come to this decision, that renders Header
component on both pages and doesn't re-render it when I switch from /first
to /second
or from /second
to /first
paths
function App() {
return (
<Route exact path={'/(first|second)'} component={Header} />
<Route exact path={'/first'} component={FirstLayout} />
<Route exact path={'/second'} component={SecondLayout} />
<Route exact path={'/third'} component={ThirdLayout} />
)
}
But if I use the method below, where FirstLayout
and ThirdLayout
components already contain Header
component, Header
component re-renders each time when I switch from /first
to /second
or from /second
to /first
paths
function App() {
return (
<Route exact path={'/fisrt'} component={FirstLayout} /> // FirstLayout already contains Header component
<Route exact path={'/second'} component={SecondLayout} /> // SecondLayout already contains Header component
<Route exact path={'/third'} component={ThirdLayout} />
)
}
So, my goal is to achieve some elegant approach in working with layouts and routes. Is there a way to make React understand that Header component should not be re-rendered in the second way?
Upvotes: 3
Views: 64
Reputation: 1694
Actually it's encouraged to use multiple Route components for different places in the UI. So your first solution seems correct.
From react router training:
// You can render a <Route> in as many places // as you want in your app. It will render along // with any other <Route>s that also match the URL. // So, a sidebar or breadcrumbs or anything else // that requires you to render multiple things // in multiple places at the same URL is nothing // more than multiple <Route>s.
Upvotes: 1