Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React 18 - Type 'null' is not assignable to type 'Element | DocumentFragment'

Tags:

reactjs

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();
like image 316
Mohammed Hashim Avatar asked Sep 02 '25 07:09

Mohammed Hashim


1 Answers

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")!);
like image 84
Mohammed Hashim Avatar answered Sep 05 '25 00:09

Mohammed Hashim