I wanted to practice React 18 and initially i got the deprecation warning and i have made the changes with createRoot. now i am facing an error stating
TS2345: Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element | DocumentFragment'. Type 'null' is not assignable to type 'Element | DocumentFragment'.
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
const root = ReactDOM.createRoot(document.getElementById("root")); // error: Type 'null' is not assignable to type 'Element | DocumentFragment'
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();
The issue here is that the return type of the document.getElementById method is HTMLElement | null. But on the other hand, the expected parameter type of the createRoot method is Element | DocumentFragment, so there is a mismatch between the provided argument type and the expected parameter type.
The right way to do is either by giving type definition of Element or using an !
const root = ReactDOM.createRoot(document.getElementById("root") as Element);
or
const root = ReactDOM.createRoot(document.getElementById("root")!);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With