Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React – open new tab once

If a component is rendered. I want to open a new tab. (window.open(url, "_blank")?.focus();)
But (during development) this tab is opened twice because of the React.StrictMode.
How can I prevent this from being called multiple times without disabling the StrictMode?

My Attempts:

function MyComp() {
    useMemo(() => window.open(url, "_blank")?.focus(), []);
    return <div>...</div>;
}

(doesn’t work (called twice))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function MyComp() {
    useEffect(() => {
        const id = setTimeout(() => window.open(url, "_blank")?.focus(), 10);
        return () => clearTimeout(id);
    });
    return <div>...</div>;
}

(works, but seems not like a good solution)

>Solution :

You simply need to keep a track of whether you have already opened the new tab.

function MyComp() {
    const openedNewTabRef = useRef(false);

    useEffect(() => {
        if (!openedNewTabRef?.current) {
            window.open(url, "_blank")?.focus();
            openedNewTabRef.current = true;
        }
    }, []);

    return <div>...</div>;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading