'Error: Target container is not a DOM element with React
I've made this React app but i keep getting this error:
Uncaught Error: createRoot(...): Target container is not a DOM element.
Can someone help me please? This is my index.html and index.js.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
ReactDOM.createRoot(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root")
);
reportWebVitals();
I've already tried every possible solutions that are uploaded to the internet, but unfortunately non of them hasn't worked yet.
Solution 1:[1]
As the docs say, the signature is:
ReactDOM.createRoot(rootNode).render(<App />);
And it replaces:
ReactDOM.render(<App />, rootNode)
So you need to change your code to
ReactDOM.createRoot(
document.getElementById("root"),
)
.render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
Solution 2:[2]
from the react documentation, https://17.reactjs.org/docs/concurrent-mode-reference.html#createroot
Replace this line of your code
ReactDOM.createRoot(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root")
);
line of your code with this code
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
This should fix the error.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CertainPerformance |
| Solution 2 | Patrick Akhamiogu |
