The error "createRoot() Target container is not a DOM element" is mostly caused by two reasons:
- When we pass the wrong id of the HTML div tag to the "document.getElementById()" method.
- The React script was placed before the div tag with id in the index.html file.
1. Wrong id in document.getElementById()
The following code is a representation of how this error could occur.
The above codes are for the root index file for a React project and the "index.html" file that exist in the "public" directory. Notice how the ids are different in these two files. This is the most common mistake that could lead to this error. Mostly this happens because of using template files on the React 18 documentation page itself while initializing the project with "create-react-app".
Solution
You need to make sure you are using the same id in both the "index.js" and "index.html" files mentioned above
2. React script file is written before the div tag with id
If you have loaded yourReact script externally to an existing website, there might be a chance that you defined your script before the div tag with id. This is a less occurring incident since it is common practice to put javascript at the end of the "body" tag in any HTML file. However, I included this as there might be a chance you could have made this mistake by accident.
If the "index.html" file in the public directory has its div tag with id placed after the React script like this:
Solution
Place the script at the bottom of the index.html file. And also note that it is common practice to call the scripts at the end of the HTML file by default. This ensures that all the components the script interacts with are already initialized and won't cause an error.
Conclusion
Passing the wrong id and wrong placement of the React script are the most common occurrence of this error. This doesn't mean that these are the only two scenarios. There are other implementation-depended occurrences of this error. For example, if you are using the HTML Webpack plugin and misconfigured the config file, this error could be triggered.
Another issue that is commonly faced by transitioning to React 18 is "ReactDOM.render is no longer supported in React 18. Use createRoot instead". Check out my below article for the solution to it.
I hope I was helpful to most of you who faced this issue. If interested, check out the featured article on my blog. Thank you.