Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Component mount issue: Target container is not a DOM element

I am trying to insert/mount a component into a DOM, but getting an error saying ‘Target container is not a DOM element’. I guess ‘mounthere’ is not getting recognized in the DOM. Where can i place this code correctly?
ReactDOM.createRoot(React.createElement(Comp1, document.getElementById("mounthere")));

DOM code:

const DOM1 = () => {
ReactDOM.createRoot(React.createElement(Comp1, document.getElementById("mounthere")));

    function1()
    {
    }

    useEffect(() => {
        window.addEventListener("scroll", handleScroll);
        return () => window.removeEventListener("scroll", handleScroll);
    }, []);

    return (
        <div class = "DOM1-container">
            <Header />
            <div class = "dom1">
                <div id = "mounthere">
                </div>
            </div>
        </div>
    );
}

Component code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Comp1 extends React.Component {
    content1 = () => {
      });
    };
    
    componentDidMount() {
      this.content1();
    }
    render() {
      return (
        <div id="div1">
        </div>
      );
    }
  }

>Solution :

In your code, you are trying to mount Comp1 into the element with id "mounthere". However, this element may not have been rendered yet when ReactDOM.createRoot() is called. useEffect can solve your problem

 useEffect(() => {
    ReactDOM.createRoot(document.getElementById("mounthere")).render(<Comp1 />);
  }, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading