How to open a link in a new tab in Reactjs

In this post, we will learn how to open a link in a new browser tab in Reactjs. I will create a starter React.js project with a button and on clicking that button, it will open a link in a new window.

Create a new project:

I am using create-react-app to create a new project for this example.

It has only one file App.js.

Method 1:

You can simply use a to add a link with target as _blank.

import './App.css';

function App() {
  return (
    <div className="App">
      <a href="https://google.com" target="_blank">Click here</a>
    </div>
  );
}

export default App;

If you are using ESLint, it will show you the below error: Reactjs open link new tab

i.e. for old browsers, if we don’t use rel with target=“_blank”, it will throw a security error.

To avoid this, you need to use rel=“noreferrer noopener”.

import './App.css';

function App() {
  return (
    <div className="App">
      <a href="https://google.com" target="_blank" rel="noreferrer noopener">Click here</a>
    </div>
  );
}

export default App;

Method 2: With a button:

We can use window.open method with a button or any other programmatic click handling. For example:

import "./App.css";

function openGoogle() {
  window.open("https://google.com", "_blank", "noopener noreferrer");
}

function App() {
  return <button onClick={openGoogle}>Click me</button>;
}

export default App;

This example uses a button and click on that button, it calls the openGoogle method and this method opens the link in a new tab.

Common function:

Let’s write down a common function to handle link clicking:

function openLink(url, newTab) {
  newTab
    ? window.open(url, "_blank", "noopener noreferrer")
    : (window.location.href = url);
}

function App() {
  return (
    <div>
      <button onClick={() => openLink("https://google.com", true)}>New Tab</button>
      <button onClick={() => openLink("https://google.com", false)}>Same Tab</button>
    </div>
  );
}

export default App;

openLink takes two parameters: the url to open and a flag to define if it needs to open the link in a new window or in the same window. If you pass true, it will open the link in a new window and if you pass false, it will open it in the same window.

In this example, I have added two buttons, the first one will open the link in a new window and the second one will open it in the same window.

You might also like: