Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Router: Apply logic to component before navigating to a different route

Is it possible to apply logic to a component before navigating to a different route?

For example, my component looks something like this:

  class Example extends React.Component {

    //Handles logic for when user leaves page
    handlePageExit = () => {
        console.log("Leaving page...");
    }

    //Set onBeforeUnload event listener so handlePageExit function is called when user closes or refreshes page
    componentDidMount = () => {
        window.addEventListener("onbeforeunload", this.handlePageExit);
    }

    //This hook is called when page exits or is refreshed 
    //It will remove event listener when 
    //However, it wont be called when user changes to a new route
    componentWillMount = () => {
        window.removeEventListener("onbeforeunload", this.handlePageExit)
    }

    //There's no react life cycle hook I can use to call HandlePageLogic when user navigates to a new route to remove event listener or apply other logic...

    render(){
        return(
          <div /> //Not relevant to question
        )
    }
}

I'm trying to apply logic such as removing event listeners before the page is navigated to the new route.

I've tried using life cycle methods such as componentWillReceiveProps, componentWillUnmount, and componentShouldUpdate to insert logic before the component is unmounted however they don't seem to be invoked when navigating to a new page.

Does anyone know where or how I can insert logic in between a route change in react-router v4?

Thank you.

like image 696
MEnf Avatar asked Dec 23 '22 07:12

MEnf


1 Answers

Yes, it is. You need to add a change listener to you react router history object.

To do this add in your componentDidMount that has the history prop:

componentDidMount() {
    this.props.history.listen(this.onRouteChange.bind(this));
  }

onRouteChange(route) {
//route.pathname = Your next route

//Handle what you need to do here
//if you need to redirect you can do this
     this.props.history.replace({pathname: '/desiredRoute'});
  }
like image 145
iNovelletto Avatar answered Dec 25 '22 19:12

iNovelletto