Using react within mvc - target container is not a dom element

47 Views Asked by At

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?

1

There are 1 best solutions below

0
lross15 On BEST ANSWER

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:

 @{
    Html.Assets().Scripts.Add("/Scripts/bundles/draftComments.bundle.js");
}

And then below the div my-comments I have done:

<script src="/Scripts/bundles/draftComments.bundle.js"></script>

Doing this solved the issue for me and now I am no longer getting that error