Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why my createdElement is doubling in reactjs useEffect()?

So my issue here is quite simple but you don’t have to understand the others codes just only the useEffect() parts..

My custom mousecursor text is doubling when I tried to hover the text

here is the lines of codes.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    const cursorIntro = document.querySelector(".cursor");
    const options = document.querySelector(".introduction .nav-options");

    options.addEventListener("mousemove", function s(e) {
      var rect = options.getBoundingClientRect();
      var x = e.clientX - rect.left; //x position within the element.
      var y = e.clientY - rect.top;
      cursorIntro.style.left = x + "px";
      cursorIntro.style.top = y + "px";
    });
    function OnSelect() {
      const optionsSelection = document.querySelectorAll(".options");
      optionsSelection.forEach((elem, i) => {
        // console.log(elem.children[1].children[0].children[0])
        elem.children[1].children[0].children[0].addEventListener(
          "mouseleave",
          () => {
            cursorIntro.removeChild(cursorIntro.lastChild);
            // cursorIntro.innerHTML = ""
          }
        );

        elem.children[1].children[0].children[0].addEventListener(
          "mouseenter",
          () => {
            // elem.children[1].children[0].children[0].classList.add('')
            const createElement = document.createElement("h4");
            createElement.innerText =
              elem.children[1].children[0].children[0].dataset.name;
            cursorIntro.appendChild(createElement);
          }
        );
      });
    }

    OnSelect();

As you see I have a custom mousecursor on it and because that is where I want to append the text when it hover the text elements.

This is inside the useEffect() when I’m calling it…but one that I wasn’t sure is that I only call back once the addEventListener per each.

The reason I used createElement because if I used innerHTML without using a createElement I can’t add another some items because my plan here is to added something more in mousecursor

THIS IS THE CODEPEN

>Solution :

go to index.js and replace StrictMode to React.Fragment, in dev mode react re-renders twice

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading