Maintaining href "open in new tab" with an onClick handler in React

Solution 1:

You have two options here, you can make it open in a new window/tab with JS:

<td onClick={()=> window.open("someLink", "_blank")}>text</td>

But a better option is to use a regular link but style it as a table cell:

<a style={{display: "table-cell"}} href="someLink" target="_blank">text</a>

Solution 2:

Most Secure Solution, JS only

As mentioned by alko989, there is a major security flaw with _blank (details here).

To avoid it from pure JS code:

const openInNewTab = (url) => {
  const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
  if (newWindow) newWindow.opener = null
}

Then add to your onClick

onClick={() => openInNewTab('https://stackoverflow.com')}

To be even terser in react, you can directly return a function

const onClickUrl = (url) => {
  return () => openInNewTab(url)
}

onClick={onClickUrl('https://stackoverflow.com')}

For Typescript + React, here is what these would look like:

export const openInNewTab = (url: string): void => {
  const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
  if (newWindow) newWindow.opener = null
}

export const onClickUrl = (url: string): (() => void) => () => openInNewTab(url)

The third window.open param can also take these optional values, based on your needs.