javascriptreactjswindow

Opening new tab reloads the first tab


In my .tsx file I have this function:

  const openTabImage = (url: string) => {
    const newWindow = window.open();
    if (!newWindow) {
        console.error("Failed to open a new tab.");
        return;
    }
    newWindow.opener = null;
    newWindow.document.body.innerHTML = 'Loading...';  // Placeholder content while loading
    newWindow.document.body.innerHTML = `<img src="${url}" alt="Document Image"/>`;
  };

Which is called when clicking on a button:

<Button
    title="Afficher l’original"
    onClick={() => openTabImage(imageSrcUrl)}
>
    Afficher l’original
</Button>

The function opens an image on a new tab (as expected).

The original tab had loaded and displayed an image and called some APIs to extract and print information from the image.

However, when the new tab is opened, the original tab gets reloaded and I lose the context.

How do I avoid the original tab from being reloaded?


Solution

  • If the <Button /> is inside a form and is the only single button inside that form, it's type is considered as submit - which by default submits your form and and takes your page to the action url (by default it's the current url). Try updating the type to button.

    <Button
        type="button"
        title="Afficher l’original"
        onClick={() => openTabImage(imageSrcUrl)}
    >
        Afficher l’original
    </Button>