problem with useEffect when re-render component. I am trying to open portal with window.open method

Viewed 41

below is my code: it's a component to create a new window using createportal and window.open method. For the first render by user-event everything is OK, but after the component unmounts and when the user initiates the new mount again it looks like useEffect does not update the state of the container - it remains 'null' and the window is not open again. Appreciate an answer much!

import { createPortal } from "react-dom";
import New_Window from "./New_Window";


function RenderInWindow({ handleOpen}) {
  const [container, setContainer] = useState();
  const newWindow = useRef(window);
  console.log(newWindow)
  
  
  useEffect(() => {
    const div = document.getElementById('portal');
    console.log(div);
    setContainer(div);
  }, []);
  

  
useEffect(() => {
    if (container) {
      newWindow.current = window.open(
        "",
        "",
        "width=810,height=520,left=300,top=300"
      );
      newWindow.current.document.body.appendChild(container);
      const curWindow = newWindow.current;
      const parentHead = window.document.querySelector("head").childNodes;
      parentHead.forEach( item => {
        curWindow.document.head.appendChild(item.cloneNode(true));
      })
      return () => { curWindow.close(); handleOpen(); }
    }
    
  }, [container]);

  const handleClose = () => {
    setContainer(null)       
  }

  return (
    
    
    container && createPortal(<New_Window  handleClose={handleClose}/>
      , container)
   
  )
};

export default RenderInWindow;
0 Answers
Related