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>
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>
Share
Improve this question
asked Apr 8, 2022 at 7:21
NoDiggityNoDoubtNoDiggityNoDoubt
5211 gold badge5 silver badges19 bronze badges
3 Answers
Reset to default 26you 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>
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.
I didn't found how to do this with useNavigation, but you can use window.open('your_url','_blank') That works for me.