I am trying to use react within my mvc application and am running into an issue and I'm not sure how to fix it.
I have the file DraftCommentsDisplay.jsx:
import React from 'react';
import ReactDOM from 'react-dom/client';
const myElement = <h1>Test</h1>;
const root = ReactDOM.createRoot(document.getElementById('my-comments'));
root.render(myElement);
Nothing really of value here but I'm just trying to get it working before actually implementing what I'm needing this file to do
This is then bundled into a file called draftComments.bundle.js through webpack so it is readable to the browser.
I am then trying to reference this file in DraftCommentsEditor.cshtml like so:
@{
Html.Assets().Scripts.Add("/Scripts/bundles/draftComments.bundle.js");
}
in this file I do have a div called my-comments like so:
<section id="comments">
<div id="my-comments"></div>
</section>
and this is within a div with an id of "draft-editors" in case that matters.
The browser can read the js file, however, I am getting the error:
Uncaught Error: createRoot(...): Target container is not a DOM element.
and it is referring to the my-comments. So I am not sure what is happening here? Is the js file being called before the document has been fully loaded? If so, how do I fix that?
Realised is that the issue was because the js file was being called before the dom had fully loaded so changed how I called the file. I got rid of this line:
And then below the div my-comments I have done:
Doing this solved the issue for me and now I am no longer getting that error