score:77
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')!;
score:0
I was also facing same error so I tried few different ways but the one that worked for me is handling null condition
i.e. const portalDiv = document.getElementById('portal')!;
score:2
I think the best solution to this is not to make it either null or HTMLDIVElement but rather in the use-case try to let typescript know that the DivElement might be empty at the moment, but you will take responsibility of it by just using "!" symbol.
Code sample below:
import React, {useEffect} from 'react';
import ReactDOM from 'react-dom';
import './modal-portlet.style.scss';
const modalRoot = document.getElementById('modalRoot');
type Props = {
children: JSX.Element;
};
const ModalPortlet: React.FC<Props> = ({children}): JSX.Element => {
const divContainer = window.document.createElement('div');
divContainer.setAttribute('class', 'modal-container');
useEffect(() => {
/**********
* immediately the component mount append @divContainer as the childNode of @modalRoot in the DOM
**********/
modalRoot!.appendChild(divContainer);
return () => {
modalRoot!.removeChild(divContainer);
};
});
/************
* return the createPortal api that takes the children(JSX) and inject it into @divContainer which is already a childNode of @modalRoot
************/
return <>{ReactDOM.createPortal(children, divContainer)}</>;
};
export default ModalPortlet;
score:4
getElementById
can return null
, but createPortal
doesn't accept null
.
If you know the portal div will exist, make the code explicit about that:
const portalDiv = document.getElementById('portal');
if (!portalDiv) {
throw new Error("The element #portal wasn't found");
}
That will allow TypeScript to narrow the type of the constant, removing the | null
part of the type. It also gives you a nice proactive warning if someone changes things such that the div isn't there when this code runs anymore.
score:7
When we select an HTMLElement inside a DOM Tree using getElementById
it returns the Element within the document that matches the specified selector, if no match is found it basically returns null.
Let's get the portal element:
let portalDiv = document.getElementById("portal");
If the portal exists in the DOM tree it will return the HTMLElemnt
in case of not found it returns null
.
So the return type of getElementById
is HTMLElement | null
, since the 2nd argument of the ReactDom.createPrortal(children: ReactNode, element: HTMLElement, id: string)
is strictly HTMLElement
we have to caste our portalDiv
to HTMLElement
inorder to get rid of the warning.
Since we are sure that the portalDiv
do exists we can use this method to deal with the null
conditions.
let portalDiv = getElementById("portal") as HTMLElement;
now we can use portalDiv
without getting any errors:
function Portal1(props) {
return ReactDOM.createPortal(
<div>
{props.children}
<div/>,
portalDiv);
}
score:11
Since getElementById
possibly returns null. So you just simply check before using like:
function Portal1({ children }) {
return portalDiv ? ReactDOM.createPortal(<>{children}</>, portalDiv) : null;
}
score:35
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
Source: stackoverflow.com
Related Query
- React Typescript - Argument of type is not assignable to parameter of type
- Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element'. Type 'null' is not assignable to type 'Element'.ts(2345)
- Argument of type 'unknown' is not assignable to parameter of type '{}'
- Argument of type 'Element' is not assignable to parameter of type 'ReactElement<any>
- react usestate hooks error: argument of type 'yyy' is not assignable to parameter of type 'setstateaction<xx>'
- getting error : Argument of type '() => () => boolean' is not assignable to parameter of type 'EffectCallback'
- Typescript React/Redux : Argument of type 'typeof MyClass' is not assignable to parameter of type 'ComponentType<...'
- React with Typescript: Argument of type 'never[]' is not assignable to parameter of type 'StateProperties | (() => StateProperties)'
- Argument of type '"MY_EVENTS_LOAD"' is not assignable to parameter of type 'TakeableChannel<unknown>' in yeild takeLatest
- React TypeScript: Argument is not assignable to parameter of type 'never'
- Argument of type 'string' is not assignable to parameter of type '`${string}` | `${string}.${string}` | `${string}.${number}`'
- Argument of type '(dispatch: Dispatch) => void' is not assignable to parameter of type 'AnyAction'
- Argument of type partial is not assignable to parameter of type
- Argument of type 'Date | null' is not assignable to parameter of type 'SetStateAction<Date>'
- React Typescript: Argument of type '{ [x: number]: any; }' is not assignable to parameter of type
- Argument of type 'number' is not assignable to parameter of type 'never' in array.includes()
- Argument of type 'string | null' is not assignable to parameter of type 'ValueFn<SVGPathElement, Datum[], string | number | boolean | null>'
- Argument of type '() => () => Promise<void>' is not assignable to parameter of type 'EffectCallback'
- Getting an error Argument of type 'unknown' is not assignable to parameter of type 'Error | null'
- Redux Toolkit - Argument of type 'AsyncThunkAction<>' is not assignable to parameter of type 'AnyAction'
- React js Typescript Argument of type 'string' is not assignable to parameter of type 'SetStateAction<number>'
- Argument of type 'Element[]' is not assignable to parameter of type 'Element'
- Redux - createStore. Argument of type is not assignable to parameter of type 'DeepPartial<any>'
- Argument of type 'AsyncThunkAction<any, void, {}>' is not assignable to parameter of type 'AnyAction'
- TS2345: Argument of type 'ReactNode' is not assignable to parameter of type 'ReactElement'
- Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'
- Argument of type 'typeof test' is not assignable to parameter of type 'Component<{ children?: ReactNode; } & DispatchProp<any>>'
- React onclick Argument of type 'EventTarget' is not assignable to parameter of type 'Node'
- TypeScript w/ React - Argument of type 'string' is not assignable to parameter of type 'keyof T'
- Argument of type 'Function' is not assignable to parameter of type 'ComponentType<never>'
More Query from same tag
- Handling File Upload state in React with hooks
- How to navigate to the first and last page antd Pagination (React)
- How import object from external JS file in React JS using web pack
- How to use 'this.props.params' in React?
- How to trigger animation using react-transition-group
- Can angular and react play together?
- Cannot load local files in electron js
- I can't add a button in a table in ReactJS
- how to call a function inside if condition in class component react?
- GraphQL & Relay Filtering UI
- how to call graphql in reactjs component (magento 2 pwa)
- Cannot read property 'setState' of undefined while updating geolocation values
- merge array object within array based on same id
- React and redux webpack config error
- Condition valid and verified multiples times except once
- Django RestFramwork how to get child component components after filter them out
- Violation 'requestIdleCallbackHandler ' took ms
- How to adjust background color for 'paper' on material-ui?
- Flow understanding A type based on another type
- React - Error : TypeError: Cannot read properties of undefined (reading 'then')
- How to accomplish customRender in React mui-Datatable
- How to change ReactJS styles dynamically?
- individual components should be connected to the store instead of just a few,
- React-Router - Link vs Redirect vs History
- Introducing errors when refactoring within <Route /> in React front end
- How do I limit the max number of item rows in a DetailsList?
- Reload component with react hooks
- Fetch API with Google Directions API is not working in reactjs
- Unmount React Parent without Unmounting Child
- Chart Piechart in only show percentage on hover but it shows data and label with percentage both i just want to show percentage only percentage