Home > Software design >  Preview URL for dynamically created link
Preview URL for dynamically created link

Time:04-05

I have a anchor tag. On click of it, I create an anchor tag and set the href attribute.

Something like this:

<a onClick={() => linkClick(url)}> Text </a>


 const linkClick = (url) => {
        const tag= document.createElement('a');
        tag.rel = 'noopener noreferrer';
        tag.target = _blank';
        tag.href = url;
        tag.click();
}

The issue I am facing here is, when I hover over the a tag, the URL preview is not available (Which usually appears at the bottom left) since href attribute is not present. Can you please help me here. (I dont want to add href attribute).

CodePudding user response:

As far as I can tell, you have the dynamic URL when you render the link. Why not just render the component fully with React? If you are going to use React to render your component, I suggest you steer clear of changing the DOM element like that afterwards.

<a 
  href={url}
  rel="noopener noreferrer"
  target="_blank"
>
  Text
</a>

CodePudding user response:

Add the href prop to the anchor tag, and then call preventDefault() in the linkClick` function like so:

<a href={url} onClick={linkClick}> Text </a>

 const linkClick = (e) => {
        e.preventDefault()
        const tag= document.createElement('a');
        tag.rel = 'noopener noreferrer';
        tag.target = '_blank';
        tag.href = e.target.href;
        tag.click();
}
  • Related