Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

229
Vistas
Can't I move element by using "element.style.top = window.scrollY"?

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;
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

 setScroll(window.scrollY+"px");  
about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda