Is there a react component event for when url query string parameters change?

Viewed 6966
4 Answers

You can use componentDidUpdate life cycle hook

componentDidUpdate(prevProps) {
  if (this.props.location !== prevProps.location) {
    console.log("Route Updated");
  }
}

If you are using react router. You can use location to achieve this behaviour. Take a look at https://reacttraining.com/react-router/web/api/location

withRouter(Component)

Your component will get query params in this.props.location.search and when query params change componentWillReceiveProps will fire.

If you are using react-router v4, you can directly use withRouter HOC to get the location prop:

import { withRouter } from 'react-router-dom';

const myComponent = ({ listen }) => {

  listen((location, action) => {
    // location is an object like window.location
    console.log(action, location.pathname, location.state)
  });

  return <div>...</div>;
};

export default withRouter(myComponent);

If you are not using react-router, here is a javascript library you can look at https://github.com/ReactTraining/history that you can manage your session history.

You can use history.listen() function to detect the route change. Here is a example:

import createHistory from "history/createBrowserHistory"

const history = createHistory()

// Get the current location.
const location = history.location

// Listen for changes to the current location.
const unlisten = history.listen((location, action) => {
  // location is an object like window.location
  console.log(action, location.pathname, location.state)
})

// Use push, replace, and go to navigate around.
history.push("/home", { some: "state" })

// To stop listening, call the function returned from listen().
unlisten()

If you are using react-router v5.

import { withRouter } from 'react-router-dom';

const myComponent = ({ history }) => {

history.listen((location, action) => {
    // location is an object like window.location
    console.log(action, location.pathname, location.state)
 });

 return <div>...</div>;
};

export default withRouter(myComponent);
Related