Skip to content

Instantly share code, notes, and snippets.

@moritzsalla
Created May 23, 2024 13:38
Show Gist options
  • Save moritzsalla/4c8b6436739cdb8ed23387a88b6b560b to your computer and use it in GitHub Desktop.
Save moritzsalla/4c8b6436739cdb8ed23387a88b6b560b to your computer and use it in GitHub Desktop.
import { useTransform, type MotionValue } from "framer-motion";
/**
* @see https://www.framer.com/motion/scroll-animations/##parallax
*
* ```tsx
* const Image = ({ id }: { id: number }) => {
* const ref = useRef(null);
* const { scrollYProgress } = useScroll({ target: ref });
* const y = useParallax(scrollYProgress, 300);
*
* return (
* <section>
* <div ref={ref}>
* <img src={`/${id}.jpg`} alt="A London skyscraper" />
* </div>
* <motion.h2 style={{ y }}>{`#00${id}`}</motion.h2>
* </section>
* );
* }
* ```
*/
export const useParallax = (
value: MotionValue<number>,
distance: number | [start: number, end: number],
) => {
return useTransform(
value,
[0, 1],
Array.isArray(distance) ? distance : [0, distance],
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment