Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

Open a link in a new tab in React

We have seen in a former article how to open a NextJs link in a new tab.

But, how can we do that in the plain old ReactJs? How can we open a link in a new tab in React?

Opening a link in a new tab in React

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.

Home Screencasts Best of Newsletter Search X