Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()

like image 333
Yassine Bridi Avatar asked Jun 29 '20 19:06

Yassine Bridi


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");
}
like image 69
MaCadiz Avatar answered Oct 19 '22 19:10

MaCadiz


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');
like image 1
Divakar Rajesh Avatar answered Oct 19 '22 20:10

Divakar Rajesh