In today’s blog post, we will learn how to open a link in a new tab in React JS. To open a link in the new browser tab we can use the anchor element and we need to set the target attribute to “_blank”.
Opening Link in New Browser Tab
<a href="https://google.com" target="_blank" rel="noopener noreferrer">
Open Link
</a>
In the above code, we are using the <a> element by setting the target attribute to “_blank”. This will open our link in a new browser tab. Also, we are using rel=”noopener noreferrer” for security reasons.
Open Link in New Tab on Button Click
function App() {
const openLink = () => {
window.open("https://timetoprogram.com", '_blank', 'noopener, noreferrer');
};
return (
<div>
<a href="https://google.com" target="_blank" rel="noopener noreferrer">
Open Link
</a>
<button onClick={openLink}>Open Link</button>
</div>
);
}
Here we are loading the resource in a new tab when the button is clicked. For that, we have written a function ‘openLink’. Inside this function, we are using the window.open() method to open the external link in a new tab.
The open() on the window object takes three parameters url, target, and windowFeatures. We pass windowFeatures as a string that contains a comma-separated list of window features.
Also, check out
Conclusion
In this post, we learned how to open a link in a new tab in React JS using the anchor element and by using the window.open() method.