React Router DOM v6 alternative for this.props.match.params, prevProps.match.params, this.props.location.pathname, prevProps.location.pathname

I have previously used React Router DOM v4 and the following:

componentDidUpdate(prevProps) {
    if ((prevProps.match.params[0] !== this.props.match.params[0])) {
        ...some code
    }
}

componentDidUpdate(prevProps) {
    if (this.props.location.pathname !== prevProps.location.pathname){
        this.loadContent();
    }
}

how should I replace them in the v6?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Use the useEffect hook with dependency to replace componentDidUpdate and the useLocation and useParams hooks to replace the location and match props.

Example:

import { useEffect } from 'react';
import { useLocation, useParams } from 'react-router-dom';

...

const{ pathname } = useLocation();
const {/* destructured param */} = useParams();

useEffect(() => {
  loadContent();
}, [pathname]);

useEffect(() => {
  ...some code
}, [/* destructured param */]);

If your question is really about how to use the [email protected] hooks with an older class component, then you’ll need to create a custom Higher Order Component to use the hooks and inject the props.

Example:

import {
  useLocation,
  useParams,
  /* other hooks */
} from 'react-router-dom';

const withRouter = Component => props => {
  const location = useLocation();
  const params = useParams();
  // other hooks

  return (
    <Component
      {...props}
      {...{ location, params, /* other hook props */ }}
    />
  );
};

export default withRouter;

Then you can decorate your class component and use the componentDidUpdate lifecycle methods and access this.props.location and this.props.params. Note that there isn’t a match prop now, e.g. this.props.match.params is now just this.props.params.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply