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:
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 />);
}, []);