To open a link in a new tab in React, we need to create an anchor (<a>
) element and set its target
attribute to _blank
.
For example: <a href="https://plainenglish.io" target="_blank">In Plain English</a>
.
The _blank
value specifies that the link should be opened in a new tab.
Let's look at a full example:
App.js
export default function App() {
return (
<div id="app">
<a href="https://plainenglish.io" target="_blank" rel="noreferrer">
In Plain English
</a>{" "}
<br />
<br /> <a
href="https://plainenglish.io/blog"
target="_blank"
rel="noreferrer"
>
In Plain English Blog
</a>
</div>
);
}
The anchor element's target attribute determines the location where the linked document should open. When not specified, the default value for target is _self, causing the linked page to open in the same tab or frame as the current page. To open the linked document in a new tab, we need to assign target with the value of _blank.
To enhance security, we also assign the rel attribute with the value of noreferrer. This prevents the opened document from obtaining any information about the page that originated the request.
Open link in new tab programmatically on button click
The ability to open a link programmatically in a new tab enables us to utilize a button instead of an anchor link to trigger the opening of a URL. We can accomplish this by attaching an onClick
event listener to the button element and invoking the window.open()
function within the listener.
For example:
App.js
export default function App() {
const openInNewTab = (url) => {
window.open(url, "_blank", "noreferrer");
};
return (
<div>
<p>Visit plainenglish.io in a new tab</p>{" "}
<button
role="link"
onClick={() => openInNewTab("https://plainenglish.io")}
>
Visit
</button>
</div>
);
}
The link will open in a new tab after the button is clicked.
Conclusion
Opening a link in a new tab can be easily achieved in React by using the window.open()
function. This method allows developers to programmatically open URLs in a new tab using a button element, providing more flexibility and control over the user's experience.
By adding the noreferrer
attribute to the link, we can also ensure greater security by preventing the opened page from accessing information about the source page.