Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which event to use when React app finishes loading

Am writing a script to be triggered when all React components has been loaded. I tried using

window.addEventListener('load')

an

document.addEventListener('DOMContentLoaded')

but both don't work very well (triggered only at the beginning)

Is there another event to listen to such that it fires only after all loading has been done?

like image 742
Stanley Avatar asked May 18 '26 02:05

Stanley


1 Answers

If you want to call external code after your React application has fully loaded, this can be done in the componentDidMount lifecycle method of your root component:

Some global code:

window.runStartupTasks = () => {
  widget.doSomething();
}

document.addEventListener('DOMContentLoaded', () => {
  ReactDOM.render(
    <RootComponent />
    document.getElementById('app-container')
  );
})

Your root component

class RootComponent extends React.Component {

  componentDidMount () {
    window.runStartupTasks();
  }

  render () {
    return (
      <div></div>
    )
  }
}
like image 191
James Hay Avatar answered May 20 '26 15:05

James Hay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!