Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect route changes with react-router v4?

I need to detect if a route change has occurred so that I can change a variable to true.

I've looked through these questions:
1. https://github.com/ReactTraining/react-router/issues/3554
2. How to listen to route changes in react router v4?
3. Detect Route Change with react-router

None of them have worked for me. Is there a clear way to call a function when a route change occurs.

like image 680
HunterLiu Avatar asked Jul 21 '18 20:07

HunterLiu


People also ask

How do I find history on react router v4?

Show activity on this post. import {useHistory } from "react-router-dom"; const TheContext = React. createContext(null); const App = () => { const history = useHistory(); <TheContext.

How do I listen to route changes in react v6 router?

Use your router and pass your history object to it. In a component you want to listen to location changes on, import your history object and invoke the listen callback as you did previously. import history from '../myHistory'; ...

How does Gatsby determine route change?

In Gatsby I can use the onRouteUpdate in gatsby-browser. js to detect route changes and this works well.


2 Answers

One way is to use the withRouter higher-order component.

Live demo (click the hyperlinks to change routes and view the results in the displayed console)

You can get access to the history object's properties and the closest 's match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md

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

class App extends Component {
    componentDidUpdate(prevProps) {
        if (this.props.location.pathname !== prevProps.location.pathname) {
            console.log('Route change!');
        }
    }
    render() {
        return (
            <div className="App">
                ...routes
            </div>
        );
    }
}

export default withRouter(props => <App {...props}/>);

Another example that uses url params:

If you were changing profile routes from /profile/20 to /profile/32

And your route was defined as /profile/:userId

componentDidUpdate(prevProps) {
    if (this.props.match.params.userId !== prevProps.match.params.userId) {
        console.log('Route change!');
    }
}
like image 83
wdm Avatar answered Sep 25 '22 07:09

wdm


With React Hooks, it should be as simple as:

useEffect(() => {
    const { pathname } = location;
    console.log('New path:', pathname);
}, [location.pathname]);

By passing location.pathname in the second array argument, means you are saying to useEffect to only re-run if location.pathname changes.

Live example with code source: https://codesandbox.io/s/detect-route-path-changes-with-react-hooks-dt16i

like image 33
parse Avatar answered Sep 22 '22 07:09

parse