Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element'. Type 'null' is not assignable to type 'Element'.ts(2345)

I have index.html

<body>
    <div id="portal"></div>
    <div id="root"></div>
</body>

and want to use the component below in separate portal div than root div,

import React from 'react';

const portalDiv = document.getElementById('portal');

function Portal1(props) {
  return ReactDOM.createPortal(
    <div>
      {props.children}
    <div/>, 
  portalDiv); //here
}

export default Portal1;

But I am getting this error, Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element'. Type 'null' is not assignable to type 'Element'.ts(2345) in VScode.

I am using Typescript. Please help.

like image 287
kishore Avatar asked Aug 21 '20 10:08

kishore


People also ask

Is not assignable to parameter of type HTMLElement?

The "Type 'HTMLElement | null' is not assignable to type" error occurs when a possibly null value is assigned to something that expects an element. To solve the error, use a non-null assertion or a type guard to verify the value is a an element before the assignment.

Does not exist on type HTMLElement?

The error "Property 'value' does not exist on type 'HTMLElement'" occurs when we try to access the value property on an element that has a type of HTMLElement . To solve the error, use a type assertion to type the element as HTMLInputElement before accessing the property. This is the index.

What is the difference between element and HTMLElement?

Technically, an HTML element is the collection of start tag, its attributes, an end tag and everything in between. On the other hand an HTML tag (either opening or closing) is used to mark the start or end of an element, as you can see in the above illustration.


2 Answers

Other people have answered that you should add a null-check, but Typescript also has a non-null assertion that you can use when you are sure that the value is never null by adding the ! operator to the end of your statement:

const portalDiv = document.getElementById('#your-element')!;
like image 112
Titulum Avatar answered Sep 16 '22 13:09

Titulum


So I dont know if anyone is still having this problem but there's an easier and straightforward solution to this. simply declare the modal element with "as" keyword
const modalRoot = document.getElementById("modal-root") as HTMLElement; This removes the error. I suggest looking through this great react-typescript cheatsheet.
https://github.com/typescript-cheatsheets/react

like image 35
Oluwaseyitan Baderinwa Avatar answered Sep 18 '22 13:09

Oluwaseyitan Baderinwa