2

I am using react-aria library for web app accessibility and I would like to render button in a new browser tab. First, I will define react-aria button:

const MyButton = props => {
    const ref = useRef();
    const { buttonProps } = useButton(props, ref);
    return <button {...buttonProps} />
}

Then, I will define component, that will render this button in a new tab

const WindowPortal = () => {
    const [isInitialized, setInitialized] = useState(false);
    const container = useMemo(() => document.createElement("div"), []);

    useEffect(() => {
        if (!container) return;
        const external = window.open("", "_blank");
        external.document.body.appendChild(container);
        setInitialized(true);
        return () => external.close();
    }, [container]);

    if (!container || !isInitialized) {
        return null;
    }

    return ReactDOM.createPortal(
        <>
            <MyButton onPress={() => console.log("My button is working!")}>My button</MyButton>
            <button onClick={() => console.log("Native button is working!")}>Native button</button>
        </>,
        container
    );
};

When <WindowPortal /> is rendered, new tab is opened and there are two buttons. When I click on the native one, everything is working. However, the react-aria one doesn't do anything on press.

Am I doing something wrong and is there any way to fix it? I have this problem not only for onPress for useButton, but for all events and interactions in react-aria.

Michal
  • 1,755
  • 3
  • 21
  • 53
  • 3
    I don't think that the new window is aware of React at all and thus it is not able to attach any functionality related to it. I tested your code and the new window opens with an about:blank URL which for sure is not under webpack's HMR domain. Also the listener doesn't work in the native button as well. Portals are meant to render something that is still inside React but outside of the app container. Maybe consider showing what you need on a different react route, or another component without a Portal. – George Makroglou Jun 26 '22 at 04:48

0 Answers0