Hello, I'm working on a React component for parallax image effect. The component:
import React, { FC, useLayoutEffect, useRef } from 'react';
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
interface ParallaxImageProps {
src: string;
alt?: string;
}
export const ParallaxImage: FC<ParallaxImageProps> = ({ src, alt }) => {
const parallaxImage = useRef(null);
const parallaxImageInner = useRef(null);
useLayoutEffect(() => {
const tl = gsap.timeline({
scrollTrigger: {
trigger: parallaxImage.current,
scroller: '.nice-scroll-container',
scrub: true,
pin: false,
},
});
tl.from(parallaxImageInner.current, {
yPercent: -10,
ease: 'none',
}).to(parallaxImageInner.current, {
yPercent: 10,
ease: 'none',
});
}, []);
return (
<figure className="parallax-image" ref={parallaxImage}>
<img
src={src}
alt={alt}
className="parallax-image__inner"
ref={parallaxImageInner}
onLoad={() => ScrollTrigger.refresh()}
/>
</figure>
);
};
I had tested onEnterand onLeavemethods and those executed in right time but animating image from yPercent: -10 to yPercent: 10 have not been working properly and have been triggering when the image comes in middle of the viewport. Any solution?
Live Demo