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.
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.
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.
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.
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')!;
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" keywordconst 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
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