Table of Contents
If you have upgraded to React 18 recently and used typescript, you would have got the following error:
Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element | DocumentFragment'. Type 'null' is not assignable to type 'Element | DocumentFragment'.
In this article, we will understand the issue and see different ways of fixing the issue.
Replicating the issue
You can replicate the issue by updating index.tsx
with the following code.
1import React from "react"2import ReactDOM from "react-dom/client"3import "./index.css"4import App from "./App"56const rootElement = document.getElementById("root")78const root = ReactDOM.createRoot(rootElement)9root.render(10 <React.StrictMode>11 <App />12 </React.StrictMode>13)
You will get the error in line number 8 where we are passing the rootElement
to ReactDOM.createRoot()
function.
Understanding the issue
The error clearly says that the type of rootElement
and
the type of the argument ReactDOM.createRoot()
function is expecting are not the same.
At first glance, you may think that it is because HTMLElement
is not assignable to Element
.
But that's not the case.
Since HTMLElement is extended from
Element, we can assign HTMLElement
to Element
.
The problem here is null
. When do we get null
as a return value for document.getElementById()
?
When the id passed to the function does not exist in the DOM.
Fixing the issue
In our case we are sure that the id root
will always exist.
Hence we can specify that rootElement
is always non-null by using ! symbol after it as shown below:
1import React from "react"2import ReactDOM from "react-dom/client"3import "./index.css"4import App from "./App"56const rootElement = document.getElementById("root")78const root = ReactDOM.createRoot(rootElement!)9root.render(10 <React.StrictMode>11 <App />12 </React.StrictMode>13)
We can also fix the issue by explicitly specifying the type of rootElement
:
1import React from "react"2import ReactDOM from "react-dom/client"3import "./index.css"4import App from "./App"56const rootElement = document.getElementById("root")78const root = ReactDOM.createRoot(rootElement as HTMLElement)9root.render(10 <React.StrictMode>11 <App />12 </React.StrictMode>13)
Do follow me on twitter where I post developer insights more often!
Leave a Comment