How to set target=_blank in React

avatar

Borislav Hadzhiev

Last updated: May 2, 2022

banner

Photo from Unsplash

Set target to _blank in React #

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

App.js
export default function App() { const openInNewTab = url => { // 👇️ setting target to _blank with window.open window.open(url, '_blank', 'noopener,noreferrer'); }; return ( <div> {/* 👇️ setting target to _blank on a link */} <a href="https://example.com" target="_blank" rel="noopener noreferrer"> Example.com </a> <hr /> <button onClick={() => openInNewTab('https://example.com')}> Example.com </button> </div> ); }

react set target blank

Notice that we have to set the rel prop to noopener noreferrer when setting target to _blank.

The noopener keyword for 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.

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://example.com" target="_blank" rel="noopener noreferrer"> Example.com </a>

Alternatively, you can set target to _blank when using the window.open() function.

App.js
export default function App() { const openInNewTab = url => { // 👇️ setting target to _blank with window.open window.open(url, '_blank', 'noopener,noreferrer'); }; return ( <div> <button onClick={() => openInNewTab('https://example.com')}> Example.com </button> </div> ); }

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

We passed the following 3 parameters 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 in the example.

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.

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.