Reputation: 1870
I have a Home.jsx
component, which has route "/"
.
"/user/:id"
)When user clicks item of the list, the list itself should disappear and the component with specified user details should appear, e.g. "/user/1"
.
When clicking the back
button or basically on page header it should go back to "/"
and show the list once again.
My approach: What I have basically done, is:
First of all, the routes (in App.jsx
):
<Route exact path="/" component={Home}/>
<Route path="/user/:id" component={Home}/>
Then, inside Home.jsx
I was playing with props:
if (this.props.match.path === '/') {
return <UserList />;
} else {
return <UserDetails userId={userId} />
}
However and unfortunately - my Home.jsx
component is being mounted with every path change - from "/"
to "/user/:id"
and back forwards. So if it re-mounts, every child component is being re-mounted aswell which causes every prop to reload which causes my app to blow...
Would really appreciate any feedback or help how to fix that issue, how to stop it re-mount with every path change. Thank you.
Upvotes: 1
Views: 178
Reputation: 20614
The entire point of <Route />
components is to handle what your if
statement is doing: conditionally render components based on the url.
You want your Home component to render on both /
and /user/:id
, not exactly on /
.
Your App.js file should look like:
<Route path="/" component={Home} />
and inside your Home.js file instead of a function with an if statement, just render <Route />
components.
You probably have something that looks like
<div>
{this.figureOutWhichComponentToShow()}
<StaticContent />
</div>
change that to:
<div>
<Route exact path="/" component={UserList} />
<Route path="/user/:id" component={UserDetails} />
<StaticContent />
</div>
and use this.props.match.params.id
inside your UserDetails component. or you can inline that in the Route
<div>
<Route exact path="/" component={UserList} />
<Route path="/user/:id" component={props =>
<UserDetails userId={props.match.params.id} />
}/>
<StaticContent />
</div>
Upvotes: 3