History.push doesn't work when redirecting to the same pathname but with different route param

Viewed 4112

I have the following route "/event/:eventId"

When the user comes from the homepage and then clicks on a card, it redirects to the event page (Everything working fine until now)

But inside of the event page, I have other cards that redirect to other events pages with different IDs as route params, and clicking on then just change the path but doesn't re-render the page.

It seems that if i'm in a page with the same pathname, doesn't matter if the route params change, it won't re-render the page.

I tried to use a <Link> component instead of the history.push but it doesn't work either.

That's the redirect function:

 const onCardClick = () => {
    history.push(
      EVENT_PAGE_LOCATION.toUrl({
        eventId: event?.id,
      }),
    );
  };


2 Answers

So turns out that the pages were being re-rendered but they weren't getting unmounted and in order to execute the graphql queries again.

So that's an important thing, React Router does not unmount the pages.

I had to refetch the queries everytime that the params changed:

useEffect(() => { 
 refetchEvent()
}, [params])

The component will re-render on route change. See below, which also works if you replace the Link with an onClick element pushing to the history object. I suspect the issue is that the content of the component has no relation to the id you are pushing. Make sure that the props passed to the component in the route reflect that id, or otherwise that the component determines its own content based on the id parameter when it mounts/changes.

const {
  BrowserRouter,
  Link,
  Route
} = window.ReactRouterDOM;

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <Route path="/:id" component={Child} />
      </BrowserRouter>
    </div>
  );
}

function Child() {
  console.log('rendered');
  const random = Math.floor(Math.random()*10);
  return <Link to={`/${random}`}>Go to {random}</Link>;
}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/react-router-dom/umd/react-router-dom.min.js"></script>
<div id="root"></div>

Related