Borislav Hadzhiev
Mon May 02 2022·2 min read
Photo by Brooke Cagle
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.
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> ); }
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.
<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.
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:
Name | Description |
---|---|
url | The URL or path of the resource to be loaded |
target | The name of the browsing context the resource is loaded to. The _blank value means that the resources is loaded into a new tab. |
windowFeatures | A 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.