Home > Back-end >  Can't I move element by using "element.style.top = window.scrollY"?
Can't I move element by using "element.style.top = window.scrollY"?

Time:11-06

I'm trying to make some kind of floating input element, making it follows the scroll. finally I made it and there is code below.

What I am wondering about is if i change "setText(window.scrollY)" to "document.querySelector(".code).style.top = window.scrollY" it doesn't give me the same result. I think it is same code but later code doesn't work. Can anybody tell me why? thank you

import React, { useState } from "react";

function Input() {
  const [scroll, setScroll] = useState(0);
  
  window.addEventListener(
    "scroll",
    function () {
      if (typeof document.querySelector(".code") === "undefined") {
        alert("TT");
      } else {
        setScroll(window.scrollY);              // *this part
      }
    },
    { passive: true }
  );

  return (
    <input
      style={{
        top: text
      }}
      className="code"
      autoComplete="on"
      placeholder="Write code please"
    />
  );
}

export default Input;

CodePudding user response:

 setScroll(window.scrollY "px");  

CodePudding user response:

Use the useRef() hook instead of document.querySelector(".code"). React works with virtual DOM, so when document.querySelector(".code") runs, the rea DOM would not be available yet. But you can use useRef to grab the virtual DOM and perform your manipulations on it. You can access the element with the ref's .current property.

Secondly, the scroll event handler would need to be wrapped in React's useEffect hook, to ensure it is added when the component mounts.

  • Related