History.push a link to a new tab with react router

Viewed 35184

I need to open a link to a new tab after doing some logic.
I have a button like this:

<Button
  onClick={handleSubmit}
>
  Preview
</Button>

with the handleSubmit() being:

const history = useHistory();

const handleSubmit = () => {
  console.log("doing something");
  history.push("/some-link") 
}

As you can see, with my usecase it wouldn't make sense to use the Link component.

So, is there a way to push that link to a new tab, using only history.push()

2 Answers

React-router's history is meant to be used just for the navigation of your application and some persistance. I can't see why you need to use it to open a new tab. I think you should use the window object for this.

const handleSubmit = () => {
  console.log("doing something");
  const win = window.open("/some-link", "_blank");
  win.focus();
}

UPDATE: Due to some comments that confirm that it is not neccesary to focus the new window we can make this solution even shorter, like:

const handleSubmit = () => {
  console.log("doing something");
  window.open("/some-link", "_blank");
}

If you simply want to open a new tab without any state transfer, you can just get the path 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');
Related