Open page in new tab on button click in React

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

Open page in new tab on button click in React #

To open a page in a new tab on button click in React:

  1. Add an onClick prop to the button.
  2. When the button is clicked, use the window.open() method to load the resource.
  3. Set the target parameter to _blank when calling the open() method.
App.js
const App = () => { const openInNewTab = url => { window.open(url, '_blank', 'noopener,noreferrer'); }; return ( <div> <button onClick={() => openInNewTab('https://google.com')}> Open google </button> </div> ); }; export default App;

The open() method on the window object loads the specified resource into a new or existing tab.

We passed the following 3 parameters to the open() method:

NameDescription
urlThe URL or path of the resource to be loaded
targetThe name of the browsing context the resource is loaded to. The _blank value means that the resources is loaded into a new tab.
windowFeaturesA comma-separated list of window features. Used for added security in the example.

When the user clicks on the button, the function we passed to the onClick prop will get invoked and the specified page will get loaded in a new tab.

Notice that we are passing a function to the onClick prop, and not the result of calling the function.

This is very important, because if we pass the result of calling the function to the onClick prop, the function would get invoked immediately as the page loads and the user's browser would open the new page without waiting on the click event.

By setting target to _blank, we open the resource in a new tab.

Technically, users are able to configure their browser to open the resource in a new window (not tab) when target is set to _blank but this is very rare.

Another target option that's commonly used is _self - which opens the URL in the current browsing context.

You can view all possibly target options in this section of the MDN docs.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.