πŸ“• LangChain for JavaScript developers is now out!
Build 5 Next.js apps with ChatGPT integrated features using LangChain.

Open a link in a new tab in React

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.

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *