Maintaining href “open in new tab” with an onClick handler in React

前端 未结 5 1669
梦如初夏
梦如初夏 2020-12-13 08:32

I have an onClick (React) handler on a table cell that fires properly, however I want to maintain the \"Open in a new Tab\" feature that having an href on a tag

相关标签:
5条回答
  • 2020-12-13 08:41

    Above answers are correct. But simply this worked for me

    target={"_blank"}
    
    0 讨论(0)
  • 2020-12-13 08:43

    React + TypeScript inline util method:

    const navigateToExternalUrl = (url: string, shouldOpenNewTab: boolean = true) =>
    shouldOpenNewTab ? window.open(url, "_blank") : window.location.href = url;
    
    0 讨论(0)
  • 2020-12-13 08:52

    You have two options here, you can make it open in a new window/tab with JS:

    <td onClick={()=> window.open("someLink", "_blank")}>text</td>
    

    But a better option is to use a regular link but style it as a table cell:

    <a style={{display: "table-cell"}} href="someLink" target="_blank">text</a>
    
    0 讨论(0)
  • 2020-12-13 08:55

    The answer from @gunn is correct, target="_blank makes the link open in a new tab.

    But this can be a security risk for you page; you can read about it here. There is a simple solution for that: adding rel="noopener noreferrer".

    <a style={{display: "table-cell"}} href = "someLink" target = "_blank" 
    rel = "noopener noreferrer">text</a>
    
    0 讨论(0)
  • 2020-12-13 09:00

    Most Secure Solution, JS only

    As mentioned by alko989, there is a major security flaw with _blank (details here).

    To avoid it from pure JS code:

    const openInNewTab = (url) => {
        const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
        if (newWindow) newWindow.opener = null
    }
    

    Then add to your onClick

    onClick={() => {openInNewTab('https://stackoverflow.com')}}
    

    The third param can also take these optional values, based on your needs.

    0 讨论(0)
提交回复
热议问题