Let's explore 2 ways of how to open a link in a new tab in React.
Opening a link in a new tab in React using the target attribute
The first obvious step is to use the target="_blank" attribute.
const newTabLink = ({url, text})=> {
return(
<a href={url} rel="noopener" target="_blank">
{text}
</a>
)
}
Keep in mind to use rel="noopener" to avoid the security vulnerability that target=β_blankβ may expose.
Opening a new tab at onClick() in React
The second option is to open a url in a new tab when the user clicks on a button or other React component.
We can do this using the window.open() method.
<button onClick={
() => window.open('https://www.js-craft.io/', '_blank', 'noopener')
}>
Go to JS Craft
</button>
Keep in mind that also in this case we will need to add the noopener parameter to avoid any phishing vulnerabilities.
Speaking of this we have seen in a former article also how to open a NextJs link in a new tab.
π Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js
π Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js