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
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: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.
It is not required, but React has a hook
useRef
, that may be more robust thandocument.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:Also, any other CSS styles updates (hover, opacity, etc.) would go into the scroll handler function.