Search code examples
reactjsreact-nativereact-routerreact-static

React route url and view changes but component function still active. Why?


I have an event function that is triggered by a button click. It's purpose is to keep the body position fixed keeping it from scrolling until you click the button again to close/toggle it off.

It works fine but, when I click to another page without toggling it off it is still active. Meaning the new page will not scroll because the body position is fixed.

I am new to React FYI

My code:

bodyFixed(event) {
  document.body.classList.add('body-fixed');
}

bodyRelative(e) {
  document.body.classList.remove('body-fixed');
}

I am using react-static withRouteData, RouteData, Router and I have no issues on those pages. But, on pages like an article page where the route doesn't change the same way. This is where I am seeing the problem.

Is there something I can wrap it with so that when I click to a new page it goes back to default?

Please first ask if you need more information and I will gladly add more.


Solution

  • Yes, you can call bodyRelative method in componentWillUnmount lifecycle hook to unset the class. Something along those lines:

    componentWillUnmount() {
      this.bodyRelative()
    }