From 94cb909700ff7bd2b4f0c04622577541ae92a278 Mon Sep 17 00:00:00 2001 From: Justin Edmund Date: Tue, 15 Sep 2020 01:24:15 -0700 Subject: [PATCH] Fix Portal --- src/Portal.tsx | 36 +++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/src/Portal.tsx b/src/Portal.tsx index 25620658..b61a47c5 100644 --- a/src/Portal.tsx +++ b/src/Portal.tsx @@ -1,7 +1,10 @@ -import { useEffect } from 'react' -import { createPortal } from 'react-dom' +import { useEffect, useRef, useState } from 'react' +import { createPortal, render } from 'react-dom' const Portal = ({ children }) => { + const el = document.createElement('div') + el.classList.add('modal_content') + let modalRoot = document.getElementById('modal') if (!modalRoot) { @@ -10,14 +13,29 @@ const Portal = ({ children }) => { document.body.appendChild(modalRoot) } - const modalElement = document.createElement('div') - - useEffect(() => { - modalRoot.appendChild(modalElement) - return () => modalRoot.removeChild(modalElement) - }) + const [val, setVal] = useState(true) - return createPortal(children, modalElement) + const modalDiv = useRef(null) + + useEffect(() => { + if (!modalDiv.current) { + modalDiv.current = el + setVal(!val) + } + }, [modalDiv]) + + useEffect(() => { + modalRoot.appendChild(modalDiv.current) + return () => { + return modalRoot.removeChild(modalDiv.current) + } + }, [modalDiv, modalRoot]) + + if (modalDiv.current) { + return createPortal(children, modalDiv.current) + } + + return null } export default Portal