NoDiggityNoDoubt
NoDiggityNoDoubt

Reputation: 521

Open new tab with useNavigate hook in React

I am trying to navigate with the useNavigate hook and everything is good, but I want it to open the URL in a new tab, and not the current one. Is that possible?

My code:

import { useNavigate } from "react-router-dom";
...
...
const navigate = useNavigate();
...
...
<Button onClick={()=>{navigate('/someURL')}}>Open URL</Button>

Upvotes: 24

Views: 51520

Answers (3)

AMRITESH GUPTA
AMRITESH GUPTA

Reputation: 312

you can use window.open() method instead of using navigate() to open the URL in the new tab. Pass '_blank' as a second argument in the function for opening it in new tab.

Importantly! If the rel="noopener noreferrer" attribute is added to the link, the referrer information will not be leaked. The end goal is not to miss the HTTP referrer title when a person clicks on a hyperlink. If there is no information in the title, it will not be tracked by analytical tools.

Example:

<Button onClick={()=>window.open('/someURL','_blank', 'rel=noopener noreferrer')}>Open URL</Button>

Upvotes: 26

hussam alhunaiti
hussam alhunaiti

Reputation: 319

A minor enhancement, with ${window.location.origin} it will navigate you from the baseUrl (current website domain), otherwise it will take the current URL and add the newRoute to it.

window.open(`${window.location.origin}/${newRoute}`)

In addition to window.open have 3 paramerets as per MDN

open(url, target, windowFeatures)

and the target is '_blank' by default so no need to add it, for more information you can read MDN doc here.

Upvotes: 8

Eduardo Miguel
Eduardo Miguel

Reputation: 1

I didn't found how to do this with useNavigation, but you can use window.open('your_url','_blank') That works for me.

Upvotes: 0

Related Questions