DEV Community

Discussion on: How to create an efficient Modal component in React using Hooks and Portals

Collapse
 
luishvdiaz profile image
Luis Humberto Vazquez Diaz

Everything looks very good! But when I pass container parameter in ReactDOM.createPortal being this "document.getElementById ('root')", it alerts me with this message: "Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element'. Type 'null' is not assignable to type 'Element'" and I know it can become null, but if I put" document.getElementsByTagName ('body') [0] "if it compiles, but that's not where I need the modal, some help?.

Collapse
 
codebucks profile image
CodeBucks

Where are you rendering your modal element? It should not the 'root'.

Collapse
 
luishvdiaz profile image
Luis Humberto Vazquez Diaz

I see, the component with id modal ... I use typescript, it keeps giving the same error message :(

Thread Thread
 
tripol profile image
Ekanem

1) You can place the document.getElementById ('root') in a variable and add a null check. For example:

const portalDiv = document.getElementById('root')!

2) Pass the portalDiv as the second parameter AFTER the </> closing fragment