skip to Main Content

I am trying to animate an image on a Vertical scroll in React.
I am using the code below!
I tried using scrollY only but then it gives error.
So when i use window.scrollY it does not give error but it does not work

import React, {useState} from 'react'

export default function Home(props) {

  const scrollhandle= () => {

const man = document.querySelector('#man');


    
    
    man.style.height = `${window.innerHeight - window.scrollY}px`
}
  

  return (
    <>
    <section id="top" >
          
          <h2 id="text"  onScroll={scrollhandle}>{text}</h2>
          <img src="https://aryan-tayal.github.io/Mountains-Parallax/man.png" id="man" alt='asdsad' />
          
          {/* <img src="https://aryan-tayal.github.io/Mountains-Parallax/mountain_left.png" id="mountain_left" style={{dispay: 'none' }} alt='asdsad'/>
          <img src="https://aryan-tayal.github.io/Mountains-Parallax/mountain_right.png" id="mountain_right" style={{dispay: 'none'}} alt='asdsad'/> */}
        </section>
        <section id="sec">
          <h2>Welcome to the Mountains</h2>
          <p>
            Lorem, ipsum dolor sit amet consectetur adipisicing elit. A earum ipsam laboriosam mollitia, architecto esse voluptates eligendi provident soluta et cupiditate sit nisi at dolorum iure dignissimos cumque amet necessitatibus blanditiis? Earum assumenda soluta reiciendis recusandae, incidunt tenetur nihil adipisci corrupti, quibusdam ullam numquam iusto veritatis facilis ab dicta, nobis inventore eius magni eveniet quo? Repellat nobis quos, facilis quam perspiciatis asperiores delectus, aliquid nihil molestias in at modi nulla minima deleniti. Minima aliquid magnam libero reiciendis et, nesciunt repellendus eum vel rerum alias ea enim fugiat eius. Quae dolores, amet nam ab officiis corrupti sequi eligendi quo culpa illum. </p>
        </section>
    
    </>
  )
}

But its not working

2

Answers


    • You should use useEffect hook when using window proprieties in react
    • And this code below will print to console the scrollY of the window on every changes in scrollY of the window
    import React, { useEffect, useState } from 'react'
    
    export default function Home(props) {
    
      const scrollhandle = () => {
        const man = document.querySelector('#man');
        console.log(window.scrollY)
        man.style.height = `${window.innerHeight - window.scrollY}px`
      }
      useEffect(() => {
        window.onscroll = () => {
          scrollhandle()
        }
      }, [window.scrollY]) 
      return (
        <>
          <section id="top" >
    
            <h2 id="text">{text}</h2> {/* text is not defined solve this proplem */}
            <img src="https://aryan-tayal.github.io/Mountains-Parallax/man.png" id="man" alt='asdsad' />
    
            {/* <img src="https://aryan-tayal.github.io/Mountains-Parallax/mountain_left.png" id="mountain_left" style={{dispay: 'none' }} alt='asdsad'/>
              <img src="https://aryan-tayal.github.io/Mountains-Parallax/mountain_right.png" id="mountain_right" style={{dispay: 'none'}} alt='asdsad'/> */}
          </section>
          <section id="sec">
            <h2>Welcome to the Mountains</h2>
            <p>
              Lorem, ipsum dolor sit amet consectetur adipisicing elit. A earum ipsam laboriosam mollitia, architecto esse voluptates eligendi provident soluta et cupiditate sit nisi at dolorum iure dignissimos cumque amet necessitatibus blanditiis? Earum assumenda soluta reiciendis recusandae, incidunt tenetur nihil adipisci corrupti, quibusdam ullam numquam iusto veritatis facilis ab dicta, nobis inventore eius magni eveniet quo? Repellat nobis quos, facilis quam perspiciatis asperiores delectus, aliquid nihil molestias in at modi nulla minima deleniti. Minima aliquid magnam libero reiciendis et, nesciunt repellendus eum vel rerum alias ea enim fugiat eius. Quae dolores, amet nam ab officiis corrupti sequi eligendi quo culpa illum. </p>
          </section>
    
        </>
      )
    }
    
    Login or Signup to reply.
  1. When the component ‘mounts’ the useEffect hook runs and adds an event listener for the scroll event. (See https://legacy.reactjs.org/docs/hooks-effect.html) The scrollHandle function is called on scroll events, which should update the height of the image based on the difference between the window’s inner height and the scroll position:

    (window.innerHeight - window.scrollY)
    

    It’s important to remove the event listener when the component is unmounted to avoid memory leaks or bubbling up issues. This is done in the ‘cleanup’ function returned by useEffect.

      useEffect(() => {
        const scrollHandle = () => {
          const man = document.querySelector('#man');
          man.style.height = `${window.innerHeight - window.scrollY}px`;
        };
    
        window.addEventListener('scroll', scrollHandle);
    
        return () => {
          window.removeEventListener('scroll', scrollHandle);
        };
      }, []);
    

    It is not required, but React has a hook useRef, that may be more robust than document.querySelector since it does not need to query the DOM on every scroll.
    The both serve very similar functions so the querySelector is fine. If you prefer the hook useRef, here is an updated example:

    import React, { useEffect, useRef } from 'react';
    
    export default function Home(props) {
      const manRef = useRef(null);
    
      useEffect(() => {
        const scrollHandle = () => {
          if (manRef.current) {
            manRef.current.style.height = `${window.innerHeight - window.scrollY}px`;
          }
        };
    
        window.addEventListener('scroll', scrollHandle);
    
        return () => {
          window.removeEventListener('scroll', scrollHandle);
        };
      }, []);
    
      return (
        <>
          <section id="top">
            <h2 id="text">{text}</h2>
            <img
              src="https://aryan-tayal.github.io/Mountains-Parallax/man.png"
              id="man"
              alt="asdsad"
              ref={manRef}
            />
          </section>
        </>
      );
    }
    

    Also, any other CSS styles updates (hover, opacity, etc.) would go into the scroll handler function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search