Ramkumar G
Ramkumar G

Reputation: 461

How to create anchor tag link that works only on right click

I have a requirement like I need to use right click for open anchor link on new tab also normal click should not work there.

The below code works good. but, if I click the link after "right click -> open new tab" action the "#" symbol added in URL like "https://example.com/currentPage#"

     <a href={void(0)}   onContextMenu={(e)=>{
                      const {currentTarget } = e;
                      (currentTarget as HTMLAnchorElement).href = "/target-link"
                      setTimeout(()=>{(currentTarget as HTMLAnchorElement).href = "#"}, 100)
                      return false;
      }}>
          click here
     </a>

so I need something like..

(currentTarget as HTMLAnchorElement).href = {void(0)}

Upvotes: 0

Views: 1195

Answers (1)

Uddesh Jain
Uddesh Jain

Reputation: 1104

You can add href as an empty string and add an onClick listener to prevent the default behavior. Like this:

<a href="" onClick={e => {
  e.preventDefault()}}
  // Some other logic
>
This is link
</a>

Upvotes: 1

Related Questions