Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload component via <Link> in React Router

I'm trying to implement a facebook-like homepage (i.e. a list of posts with comments).

PostList is the component in charge of loading the post list (using fetch in its componentDidMount() ), itself being a child of the component HomePage.

I have another component for the navigation bar called NavBar with a <Link> component (from react-router-dom) to the route of my HomePage component ('/').

When I'm on any page other than '/', using the link works fine: the Router mounts HomePage, and then PostList triggering the componentDidMount() and displaying the freshly retrieved posts.

But when I'm already on '/' the Link does nothing because well I'm already on '/', but I'd like it to still reload my component HomePage so it can update its post list.

How can I do it ?

like image 528
Sara Doe Avatar asked Dec 13 '22 19:12

Sara Doe


2 Answers

A React component re-renders only when it is given different props (or when it's state changes).
I had an issue similar to yours, and I solved it by passing a timestamp prop to the component everytime. That solved the issue for me. So inside you <Router> component, where you define the route for Home component, use the following code:

<Route path='/' component={ (props) => (
  <Home timestamp={new Date().toString()} {...props} />
)}/>

This way, the timestamp prop changes on subsequent clicks, and the component re-renders everytime you click the <Link>.

like image 156
Dane Avatar answered Dec 17 '22 23:12

Dane


I was solving a similar problem today. I had route:

<Route exact path="/:id" render={({ match }) => (<MyComponent match={match} />)} />

and link which did not invoke reload if newId was same as rendered id:

<Link to={{ pathname: `/${newId} }} >Go</Link>

The simplest solution I found was adding new reload redirect (right under route):

<Redirect from="/:id/reload" to="/:id" />

and changing link for newId === id to

<Link to={{ pathname: `/${id}/reload` }} >Reload</Link>

I also found a solution with adding new route with added timestamp (like 1567430708808):

<Route exact path="/:id/:ts" render={({ match }) => (<MyComponent match={match} />)} />

and reading it from match object for hooks, but timestamp occurred in URL and it was not as nice as the redirect. I need to mention I use react-router 5.0.1.

like image 21
rinkishimo Avatar answered Dec 17 '22 22:12

rinkishimo