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

135
Vistas
Creating Parallax effect using setState

Currently what I'm trying to achieve is this, where 1 image moves from left to right as the user scrolls down creating a parallax effect:

enter image description here

Normally with DOM I would use:

let image = document.getElementById("image");

window.addEventListener('scroll', function() {
  let value = window.scrollY;
  image.style.marginRight = value * 4 + 'px';
  image.style.marginTop = value * 1.5 + 'px';
}

But currently I'm trying to replicate this effect in React using setState, but the image doesn't move along with mouse scroll wheel and the layout does not seem right. So far I've made the effect for when my scroll is between 1 and 300px height where my image moves from center to left side. But I want it so that after 300px till 600px, the image should move from left to right as seen in reference image.

CodeSandBox: https://codesandbox.io/s/modest-hill-2wuko

Current Code:

const [leftScroll, setLeftScroll] = useState(false);
  const [topScroll, setTopScroll] = useState(false);
  const [textScroll, setTextScroll] = useState(false);

  useEffect(function onFirstMount() {
    const changeBackground = () => {
      let value = window.scrollY;
      console.log(window.scrollY);

      if (value > 0 && value < 300) {
        setLeftScroll(true);
        setTopScroll(true);
        setTextScroll(true);
      } else {
        setLeftScroll(false);
        setTopScroll(false);
        setTextScroll(false);
      }
    };

    window.addEventListener("scroll", changeBackground);

    return null;
  }, []);
  return (
    <div className="background">
      <div
        style={{
          backgroundColor: "#0E2043",
          padding: "50px",
          height: "1000px",
          display: "flex",
          justifyContent: "center"
        }}
      >
        <div className="header">Vanuatu</div>
        <img
          className="image"
          style={{
            marginRight: leftScroll ? "300px" : "0px",
            transition: "2s",
            marginTop: topScroll ? "300px" : "0px"
          }}
          alt="random"
          src="https://cdn.britannica.com/87/122087-050-1C269E8D/Cover-passport.jpg"
        />
        <div
          className="text"
          style={{
            marginTop: textScroll ? "300px" : "800px",
            transition: "4s",
            marginLeft: "120px"
          }}
        >
          Minimum Investment
        </div>
      </div>
    </div>
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Like Andy mentioned in the comments, you don't want to use useState for animations like this. If you already have the code for this feature without React, you can mostly use it in your React code as well. Except that you want to use useRef to create a reference to the elements you want to animate.

Also, don't forget to clean up your event listener after the component unmounts.

  const imageRef = useRef();
  const textRef = useRef();

  useEffect(function onFirstMount() {
    const changeBackground = () => {
      let value = window.scrollY;

      if (value > 0 && value < 300) {
        textRef.current.style.marginTop = "300px";
        imageRef.current.style.marginRight = "300px";
        imageRef.current.style.marginTop = "300px";
      } else {
        textRef.current.style.marginTop = "800px";
        imageRef.current.style.marginRight = "0px";
        imageRef.current.style.marginTop = "0px";
      }
    };

    window.addEventListener("scroll", changeBackground);

    return () => window.removeEventListener("scroll", changeBackground);
  }, []);

  return (
    <div className="background">
      <div
        style={{
          backgroundColor: "#0E2043",
          padding: "50px",
          height: "1000px",
          display: "flex",
          justifyContent: "center"
        }}
      >
        <div className="header">Vanuatu</div>
        <img
          ref={imageRef}
          className="image"
          style={{ transition: "2s" }}
          alt="random"
          src="https://cdn.britannica.com/87/122087-050-1C269E8D/Cover-passport.jpg"
        />
        <div
          ref={textRef}
          className="text"
          style={{
            transition: "4s",
            marginLeft: "120px"
          }}
        >
          Minimum Investment
        </div>
      </div>
    </div>
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