4

I am building a project with react-router that has multiple routes. The code looks like this:

<Router>
  <div className='main'>
    <Header />
    <div className='main-content'>
      <Switch>    
        <Route exact path="/about" render={({history: {location}}) => <About/>}/>
        <Route exact path="/contact" render={({history: {location}}) => <Contact/>}/>
        <Route exact path="/blog" render={({history: {location}}) => <Blog/>}/>
      </Switch>
    </div>
    <Footer /> 
  </div>
</Router>

In the component for each route I am adding a lifecycle method ComponentDidMount(), setting an event listener for 'load' and then running a callback.

componentDidMount() {
  window.addEventListener('load', () => this.handleLoad());
}

handleLoad() {
  console.log('this page loaded');
}

This works as expected on the first route that loads and the console will log 'this page loaded'. However, when any subsequent route is requested the event listener no longer listens for load of the next component (maybe because the event listener is still in place?)

How can I listen for page load on multiple routes?

Joel Hoelting
  • 1,413
  • 12
  • 37
  • 2
    When do you expect the `load` event to fire? It will only fire once when the browser initially loads, after all the resources have finished loading. – Tholle Nov 08 '18 at 22:08
  • When React switches a route, it's just modifying content on the page, not loading a new page, so the `load` event won't fire a second time. – Herohtar Nov 08 '18 at 22:08
  • React router doesn't cause a page load the browser isn't actually navigating to a new url – Patrick Evans Nov 08 '18 at 22:09
  • I understand all of the above but I have assets on each route that load each time a route switches. Is there a way to listen for when the content on each route finishes loading? – Joel Hoelting Nov 08 '18 at 22:09
  • What are you trying to do with it? `componentDidMount` will fire when the component for your route is mounted. – Herohtar Nov 08 '18 at 22:12
  • Possible duplicate of [Detect Route Change with react-router](https://stackoverflow.com/questions/45373742/detect-route-change-with-react-router) – Patrick Evans Nov 08 '18 at 22:12
  • 1
    @PatrickEvans I am not looking to detect route change, I want to perform actions after all the content in a component of the new route loads. – Joel Hoelting Nov 08 '18 at 22:17
  • https://www.javascriptstuff.com/detect-image-load/ – Herohtar Nov 08 '18 at 22:26
  • 2
    @Herohtar Thanks for that resource. I am in fact waiting for images to load. The component is rendering/mounting but the images load after the component renders. I can work with this. Thank You – Joel Hoelting Nov 08 '18 at 22:30

1 Answers1

0

Based on my knowladge whole react app loads on user pc at once, and then it just changes the look based on routes, and won't take any time to load. But you can listen api fetchs if you want.