Home > Software engineering >  Why my createdElement is doubling in reactjs useEffect()?
Why my createdElement is doubling in reactjs useEffect()?

Time:06-02

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.

    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

CodePudding user response:

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

  • Related