How to Open a Component in New Window on a Click in React?

Sometimes, we want to open a component in new window on a click in React.

In this article, we’ll look at how to open a component in new window on a click in React.

Open a Component in New Window on a Click in React

To open a component in new window on a click in React, we can call window.open with the element we created.

For instance, we write:

import React, { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";

const RenderInWindow = (props) => {
  const [container, setContainer] = useState(null);
  const newWindow = useRef(window);

  useEffect(() => {
    const div = document.createElement("div");
    setContainer(div);
  }, []);

  useEffect(() => {
    if (container) {
      newWindow.current = window.open(
        "",
        "",
        "width=600,height=400,left=200,top=200"
      );
      newWindow.current.document.body.appendChild(container);
      const curWindow = newWindow.current;
      return () => curWindow.close();
    }
  }, [container]);

  return container && createPortal(props.children, container);
};

export default function App() {
  const [open, setOpen] = useState();
  return (
    <>
      <button onClick={() => setOpen(true)}>open</button>
      {open && <RenderInWindow>hello world</RenderInWindow>}
    </>
  );
}

to create the RenderInWindow component that opens a new window when it mounts.

To do this, we create the container state with useState.

And we create a ref to store the window object.

In the first useEffect callback, we create a div that we use as the content of the element when RenderInWindow mounts and call setContainer to set the div as the value of `container.

In the 2nd useEffect callback, we check if container is set.

If it is, then we call window.open and set the returned window object as the value of newWindow.current.

And we set the content of the window with:

newWindow.current.document.body.appendChild(container);

And then we get newWindow.current and set it to curWindow.

Finally we return a function that calls curWindow.close to close the window when the component unmounts.

Then we return a portal with the window.

We get the content of the window from the children prop.

In App, we render the RenderInWindow component with the content of the popup window when open is true.

And we make open true when we click on open.

Therefore, we should see ‘hello world’ displayed in a popup window when we click on open.

Conclusion

To open a component in new window on a click in React, we can call window.open with the element we created.