Home > Mobile >  How do I add Wikipedia style references in my ReactJS application?
How do I add Wikipedia style references in my ReactJS application?

Time:10-17

I want to create superscript tags, which if clicked upon, redirect the user to the references, like in Wikipedia.

Now, I created the superscript tag and tried setting href attribute to it, but nothing happens when I click, even though the inspect element shows that the href attribute has been properly applied to sup tag.

This is what I tried:

useEffect(() => {
    let sup = document.querySelectorAll("sup");

    if(sup && sup.length > 0 ) {

    sup[0].setAttribute("href", 'https://www.google.com');
    console.log(sup, "sup")
    
    }
  }, [articles])

CodePudding user response:

sup element doesn't have href attribute, and can't navigate too.

You need to inject inside an anchor tag with href of the link you need to navigate to.

let sup = document.querySelectorAll("sup");

if (sup && sup.length > 0) {
  sup[0].innerHTML = `<a href="https://www.google.com">${sup[0].innerHTML}</a>`
}
link<sup>1</sup>

CodePudding user response:

You appear to be adding href to the sup tag, which won't work. Will only work on a tag.

Also, unless I'm missing something, you are overcomplicating things by using JS to create the link / tag. You can simply put the link inside the a tag in your HTML:

lorem ipsum <sup><a href="https://example.com">link</a></sup>

CodePudding user response:

The main important thing you need to change in your code is wrap your <sup> tag in an <a> tag, so then you can add a href attribute to <a> tag and then on user click you can successfully let user go through the link you will provide.

For example:

    useEffect(() => {
       ...
       const anchorEl = document.createElement("a");
       anchorEl.setAttribute("href", 'https://www.google.com');

       const supEl = sup[0]         
       anchorEl.appendChild(supEl);
       
       supEl.parentNode.replaceChild(anchorEl, supEl);      
       // supEl.replaceWith(anchorEl) // it does the same as above line, but very old browsers may not support *replaceWith* method.
       ...
    },[articles])

Also here you can read about what can help you better understand about <sup> tags and why you should wrap them in a <a> tag: Turn all <sup> elements into links

And the last thing I want to note that directly manipulating DOM elements through useEffect hook is not React considers in the first place as the way for doing such changes into a DOM, and React is well designed to update the DOM through JSX and Virtual DOM, when state or props of the component is changed, which is a React default behavior. So, you don't have to do much things when React already can do it for you easily, and if you organize your components, logic and your code at all properly, you can get the most out of React.

  • Related