Skip to content

Instantly share code, notes, and snippets.

@sidd
Created September 2, 2022 17:56
Show Gist options
  • Save sidd/4e59698a6066cc8b5c20fce5176ff775 to your computer and use it in GitHub Desktop.
Save sidd/4e59698a6066cc8b5c20fce5176ff775 to your computer and use it in GitHub Desktop.
const Parallax = ({ children, offset = 50, className }: ParallaxProps): JSX.Element => {
const prefersReducedMotion = usePrefersReducedMotion();
const [elementTop, setElementTop] = useState(0);
const [clientHeight, setClientHeight] = useState(0);
const ref = useRef(null);
const { scrollY } = useViewportScroll();
const initial = elementTop - clientHeight;
const final = elementTop + Math.abs(offset);
const yRange = useTransform(scrollY, [initial, final], [offset, -offset]);
const x = useSpring(yRange, { stiffness: 400, damping: 90 });
useEffect(() => {
const onResize = () => {
const element = ref.current;
if (!element) return;
setElementTop(element.getBoundingClientRect().top + window.scrollY || window.pageYOffset);
setClientHeight(window.innerHeight);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment