Open a link in a new tab in React

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Open a link in a new tab in React #

To open a link in a new tab in React, use the <a> element and set its target prop to _blank, e.g. <a href="https://google.com" target="_blank" rel="noopener noreferrer"></a>. The _blank value means that the resource is loaded into a new tab.

App.js
export default function App() { const openInNewTab = url => { window.open(url, '_blank', 'noopener,noreferrer'); }; return ( <div> {/* 👇️ open link in new tab */} <a href="https://google.com" target="_blank" rel="noopener noreferrer"> Google </a> <hr /> {/* 👇️ open link in new tab using a button */} <button onClick={() => openInNewTab('https://google.com')}> Google </button> </div> ); }

open link in new tab

The code snippet shows how to open a link in a new tab using an anchor tag and a button element.

When the target prop of the a element is set to _blank, the resource is loaded into a new tab.

App.js
<a href="https://google.com" target="_blank" rel="noopener noreferrer"> Google </a>

We set the rel prop to noopener noreferrer for security purposes.

The noopener keyword of the rel attribute instructs the browser to navigate to the target resource without granting the new browsing context access to the document that opened it.

Alternatively, you can set an onClick prop on an element and call the window.open() method to load a resource in a new tab.

App.js
export default function App() { const openInNewTab = url => { window.open(url, '_blank', 'noopener,noreferrer'); }; return ( <div> {/* 👇️ open link in new tab using a button */} <button onClick={() => openInNewTab('https://google.com')}> Google </button> </div> ); }

The open() method on the window object loads the specified resource into a new or existing tab.

We passed the following 3 arguments to the open() method:

NameDescription
urlThe URL or path of the resource to be loaded
targetThe name of the browsing context the resource is loaded to. The _blank value means that the resources is loaded into a new tab.
windowFeaturesA comma-separated list of window features (used for added security)

When the user clicks on the button, the function we passed to the onClick prop will get invoked and the specified page will get loaded in a new tab.

Notice that we are passing a function to the onClick prop, and not the result of calling the function.

This is very important, because if we pass the result of calling the function to the onClick prop, the function would get invoked immediately as the page loads and the user's browser would open the new page without waiting on the click event.

By setting target to _blank, we open the resource in a new tab.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.