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 *

Home Screencasts Best of Newsletter Search X

πŸ“– 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X