Due to the lack of direct support in react-animate-on-scroll
for adjusting animations based on scrolling direction, one workaround is to utilize state variables and event listeners for scroll tracking.
For Node.js and NPM users, you can use window.pageYOffset
to determine the scrolling direction by comparing it with the current scroll position.
'if the currentScrollPos is greater than the windows vertical scroll
position'
In code, this logic would look like:
currentScrollPos > (window.scrollY || window.scrollTop) ? 'down' : 'up'
To handle the scroll events, you can employ the useEffect hook along with event listeners. Most modern browsers support window.scrollY
, which indicates the current vertical scroll position. Additionally, using window.scrollTop
serves as a fallback for older browser compatibility.
import React, { useEffect, useState } from 'react';
import ScrollAnimation from 'react-animate-on-scroll';
function MyComponent() {
const [scrollDirection, setScrollDirection] = useState('down');
useEffect(() => {
const handleScroll = () => {
const currentScrollPos = window.pageYOffset;
const scrollDirection = currentScrollPos > (window.scrollY || window.scrollTop) ? 'down' : 'up';
setScrollDirection(scrollDirection);
};
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
return (
<ScrollAnimation animateIn={scrollDirection === 'down' ? 'fadeInUp' : ''} duration={0.7}>
<h1 className='mb-4'>Text with animation</h1>
</ScrollAnimation>
);
}
export default MyComponent;