0

I build with webpack and transpile with babel. The pages are generated in php. Once the js bundles are loaded, I want to mount a React component.

I have been using jQuery for this, but it seems wrong to me, and I guess there is a better way. Could you help me with this?

Here's how it works now:

import $ from "jquery";

const documentReadyPromise = Symbol('documentReadyPromise');

window[documentReadyPromise] = new Promise(function(resolve) {
    $(() => {
        resolve();
    });
});

export function getDocumentReadyPromise() {
    return window[documentReadyPromise];
}

/**
 * Gets a promise that gets resolved as soon as React can be used
 *
 * @returns {Promise}
 */
export function getReactReadyPromise() {

    // React can be used as soon as:
    return Promise.all([

        // a) document is ready
        window[documentReadyPromise]

        // AND b) .... etc - add more entries here
    ]);
}

And then I use it like this:

getReactReadyPromise().then(() => {
    ReactDOM.render(
        <MyComponent />,
        document.getElementById('my-component-mount-point')
    );
});
Meglio
  • 1,263
  • 1
  • 14
  • 26
  • I recommend to use the [DOMContentLoaded event](https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event). – Martin Apr 19 '21 at 13:47
  • My question got marked as "already answered". However, the other question referenced is not the same. My questions is for a case specific to using webpack and/or babel. I am hoping that when using webpack and/or babel, there is a special tool that I can leverage to run code on DOM ready state. – Meglio Apr 20 '21 at 02:14
  • 1
    There is no special way in which DOM ready / loaded is handled in webpack and babel projects. The [document.readyState](https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState) is used to check if the loaded event already fired, and the DOMContentLoaded event is used to have a callback invoked once at the point in time when this happens. That is part of your initialization code in some file of yours. – Martin Apr 20 '21 at 07:31

0 Answers0