createPortal in document.body
Hi !
Please, write in the documentation, if createPortal(<SomeComp />, document.body) is a bad or potentially dangerous practice. I have not found an official answer to this question.
I have never used the createPortal() on body tag.if you had seen any bad effects. Just write and make an PR in the Reactdocs. ReactDocs is also open source :)
@alexandroppolus
const Modal: React.FC<ModalProps> = ({ children, size = 'm', open, onClose, closable = true }) => {
const dialogContainer = useRef<HTMLDivElement>(null);
useEffect(() => {
if (open) {
noScroll.on();
}
return () => {
noScroll.off();
};
}, [open]);
const clickedOutsideZone = (event: HTMLElementEventMap['mousedown'] | HTMLElementEventMap['touchstart']) => {
const containerNoClosable = event.target as Node;
const isClickedOutside = dialogContainer.current && dialogContainer.current.contains(containerNoClosable);
if (isClickedOutside) return;
onClose?.();
};
const removeEvents = (): void => {
document.removeEventListener('mousedown', clickedOutsideZone);
document.removeEventListener('touchstart', clickedOutsideZone);
};
useEffect(() => {
if (open && closable) {
document.addEventListener('mousedown', clickedOutsideZone);
document.addEventListener('touchstart', clickedOutsideZone);
} else removeEvents();
return () => removeEvents();
}, [onClose, open, closable]);
return ReactDOM.createPortal(
<ContainerModalBackground open={open}>
<div
style={{
display: 'flex',
width: '100%',
justifyContent: 'center',
alignItems: 'center',
height: '100%',
}}
>
{open && (
<ContainerModal size={size} ref={dialogContainer}>
{size !== 'full' && <FocusLock>{open && children}</FocusLock>}
{size === 'full' && open && children}
<CloseButtonContainer onClick={onClose}>
<Close color={dismissDarker} />
</CloseButtonContainer>
</ContainerModal>
)}
</div>
</ContainerModalBackground>,
document.body
);
};
export default Modal;
I have seen that many large libraries use portals with document.body, so far it has not given me any problems.
I have seen that many large libraries use portals with document.body, so far it has not given me any problems.
It's a perf issue as far as I know: https://atfzl.com/don-t-attach-tooltips-to-document-body
This issue has been automatically marked as stale. If this issue is still affecting you, please leave any comment (for example, "bump"), and we'll keep it open. We are sorry that we haven't been able to prioritize it yet. If you have any new additional information, please include it with your comment!
Closing this issue after a prolonged period of inactivity. If this issue is still present in the latest release, please create a new issue with up-to-date information. Thank you!