How to open a link in a new tab in React?

To open a link in a new tab, use the target prop of the anchor element and set its value to _blank.

App.js
import React from 'react';

export default function App() {

  return (
    <a href="https://www.youtube.com" target="_blank">YouTube</a>
  );
}

Output

Open a link in a new tab in React

In this example, we have used the target prop, and its value is set to _blank.

You can also open a URL in a new tab on the click of a button using the window.open() method.

window.open() method accepts three parameters:

Parameter Description
url URL or the path of the resource that you want to load.
target The browsing context in which the resource is to be loaded. The _blank value loads the resource in a new tab.
windowFeatures It is a comma-separated list of windows features. Windows features such as width and height of the content area, the top-left position of the tab, etc. are set using this parameter.
App.js
import React from 'react';

export default function App() {
  function newTab() {
    window.open('https://www.youtube.com', '_blank');
  }

  return (
    <button onClick={newTab}>Click Here</button>
  );
}

Output

window.open() to open a link in React

Recommended Posts