React: Re-render a Component On Route Change

  • In other words: reloading/refreshing the same React component when visiting a link.
  • It makes sense to have a single React component for calling the API endpoints depending on the location pathname.
  • As you can see TableContainer is the only React component for fetching data.
  • More about presentational and container components: writing React components – – It should call the appropriate endpoint whenever I click /subscribers or /leads.
  • A single React component can fetch the data from different endpoints depending on the location pathname.

A common scenario with React Router: re-render a component on route change

A common scenario with React Router: re-render a component on route change.

In other words: reloading/refreshing the same React component when visiting a link.

The same concept applies for re-rendering a component when props change.

How do you write such logic? Let’s find out together!

Originally published on valentinog.com/blog on February 20, 2018

React: re-render a component on route change. The use case

React promotes component reusing.

You don’t want to write 2 different components for calling 2 separate endpoints.

It makes sense to have a single React component for calling the API endpoints depending on the location pathname.

Consider an application in which React router handles the routing part.

When visiting https://example.app/subscribers I want to call api/subscribers/.

And by clicking https://example.app/leads I want to call api/leads/.

Here’s the code:

As you can see TableContainer is the only React component for fetching data.

TableContainer acts as a container for another component: Table.

More about presentational and container components: writing React components

It should call the appropriate endpoint whenever I click /subscribers or /leads.

available to its children.

Plus we know that componentDidMount is a good place for making AJAX calls in React.

That leads me to write something like:

With the application in place I can…

React: Re-render a Component On Route Change