45

I am using ReactJS for a project along with React Router (no redux) I want to programmatically open a link but on a new tab. I am aware that using onClickNode={e => this.props.history.push('/${e.data.node.id}')} I can go to the desired link but the problem is that it gets opened in the same tab. Also there is no way to use JSX in that function and hence no possibility of adding <Link> component.

( I am using React Router v4)

Aron Karmer
  • 1,911
  • 2
  • 12
  • 15
  • 1
    This can help even if they don't use react https://stackoverflow.com/questions/427479/programmatically-open-new-pages-on-tabs – William Dec 13 '17 at 09:20
  • Possible duplicate of [Programmatically open new pages on Tabs](https://stackoverflow.com/questions/427479/programmatically-open-new-pages-on-tabs) –  Dec 13 '17 at 10:59

5 Answers5

91

This https://stackoverflow.com/a/11384018/7697399 answer helped me out and worked flawlessly. This could be done without the help of react-router.

function openInNewTab(url) {
  var win = window.open(url, '_blank');
  win.focus();
}
Aron Karmer
  • 1,911
  • 2
  • 12
  • 15
18

Similar to the previous answer, but doesn't error out if the window couldn't be opened.

function open(url) {
  const win = window.open(url, '_blank');
  if (win != null) {
    win.focus();
  }
}
Ares
  • 1,411
  • 1
  • 19
  • 35
6

<Link/> component from react-router-dom can be used. Using you can pass props to new tab.

<Link to='/' target="_blank"> 
  <div> Button </div>
 </Link>
Penguin
  • 169
  • 3
  • 14
6

In new Javascript syntax you could write the function like so:

const openLink = (url) => window.open(url, '_blank')?.focus();

This will try to open the URL in a new tab and focus on it if succeeded. It will not throw an error if the tab did not open.

Ethan Wass
  • 95
  • 1
  • 10
1

You can get the path programatically using useHref hook(Docs). This is what the <Link> component internally uses. You can then open it in new tab using window.open. This would automatically add the basename etc for you.

let href = useHref(to);
window.open(href, '_blank');
Divakar Rajesh
  • 1,140
  • 2
  • 18
  • 23