Home > Back-end >  How to handle popup in React Router
How to handle popup in React Router

Time:11-22

I have React Router wrapping my root div but I can't seem to figure out how to handle a popup window when a link is clicked.

I know I can instead load a static HTML page in the public folder but I'd like it to be a .js file in src.

This is what I want:

import { Link } from "react-router-dom";

import Test from './pages/test.js';


function Example() {
  return (
    <>
    <Link onClick={() => window.open(<Test />, "Popup", "toolbar=no, location=no, statusbar=no, menubar=no, scrollbars=1, resizable=0, width=650, height=400, top=30")}>
     Hello
    </Link>
    </>
  );
}

export default Example;

This is the only thing that works and then I obviously lose the functionality of React (unless I'm looking at it wrong?) The URL path is to a directory in public

import { Link } from "react-router-dom";

import Test from './pages/test.js';


function Example() {
  return (
    <>
    <Link onClick={() => window.open('/example', "Popup", "toolbar=no, location=no, statusbar=no, menubar=no, scrollbars=1, resizable=0, width=650, height=400, top=30")}>
     Hello
    </Link>
    </>
  );
}

export default Example;

CodePudding user response:

on react we use portals instead of pop ups, learn about it here is an example

https://codesandbox.io/s/h4zv0

CodePudding user response:

I dont know why you want to do that XD but the window.open only have a URL or "", like firts parameter, but you can create a portal with react-dom or a reactDom.render:

create a portal: https://stackoverflow.com/a/71907023/13625491

with reactDom.render:

onClick={() => {
          var myWindow = window.open(
            "",
            "Popup",
            "toolbar=no, location=no, statusbar=no, menubar=no, scrollbars=1, resizable=0, width=650, height=400, top=30"
          );
          myWindow && ReactDOM.render(<ReactElement color="error" variant="contained">this is a element of react</ReactElement>,  myWindow.document.body);
        }}
  • Related