People always say that you can get the dom
in componentDidMount
.
Is that mean componentDidMount
and DOMContentLoaded
are synchronous, or does it mean when componentDidMount
, the dom
is always ready?
The DOMContentLoaded
event is exclusive to when the entire HTML page loads. Therefore, this event is only fired once and only once, throughout the entirety of the web page's lifetime. componentDidMount
, on the other hand, is called when a React component is rendered. Therefore, it is entirely possible for componentDidMount
to be called several times, albeit for entirely different instances of the same component's class.
And yes, the browser's DOM is always in the "ready state", at the time when a componentDidMount
event is called.
The react componentDidMount
is fired before the DOMContentLoaded
and the DOM is ready here.
Have a look at console log in this demo: http://codepen.io/PiotrBerebecki/pen/EgdkXB
It logs the following:
componentDidMount: React rendered! DOMContentLoaded before class: React rendered! DOMContentLoaded after class: React rendered! DOMContentLoaded in constructor: React rendered! DOMContentLoaded in render: React rendered! DOMContentLoaded in componentDidMount: React rendered! DOMContentLoaded after ReactDOM.render: React rendered!
Full code:
document.addEventListener('DOMContentLoaded', function(event) { console.log('DOMContentLoaded before class:', document.getElementById('app').textContent); }); class App extends React.Component { constructor() { super(); document.addEventListener('DOMContentLoaded', function(event) { console.log('DOMContentLoaded in constructor:', document.getElementById('app').textContent); }); } componentDidMount() { document.addEventListener('DOMContentLoaded', function(event) { console.log('DOMContentLoaded in componentDidMount:', document.getElementById('app').textContent); }); console.log('componentDidMount:', document.getElementById('app').textContent); } render() { document.addEventListener('DOMContentLoaded', function(event) { console.log('DOMContentLoaded in render:', document.getElementById('app').textContent); }); return ( <div> React rendered! </div> ); } } document.addEventListener('DOMContentLoaded', function(event) { console.log('DOMContentLoaded after class:', document.getElementById('app').textContent); }); ReactDOM.render( <App />, document.getElementById('app') ); document.addEventListener('DOMContentLoaded', function(event) { console.log('DOMContentLoaded after ReactDOM.render:', document.getElementById('app').textContent); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With