Home > database >  React - How to assign "void(0)" to anchor tag href using Javascript ( event.target.href )
React - How to assign "void(0)" to anchor tag href using Javascript ( event.target.href )

Time:07-06

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)}

CodePudding user response:

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>

CodePudding user response:

Thanks @Uddesh Jain, it works

The complete working code is

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