最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Open new tab with useNavigate hook in React - Stack Overflow

programmeradmin1浏览0评论

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
Add a comment  | 

3 Answers 3

Reset to default 26

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>

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.

发布评论

评论列表(0)

  1. 暂无评论