Skip to content

Commit

Permalink
Rewrite parallax to it's cleaner
Browse files Browse the repository at this point in the history
  • Loading branch information
yvonnetangsu committed Apr 4, 2024
1 parent c091390 commit 02c20d4
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 30 deletions.
39 changes: 10 additions & 29 deletions components/Parallax/Parallax.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,41 +19,22 @@ type ParallaxProps = {
children: ReactNode;
};

/**
* Using guide from https://samuelkraft.com/blog/spring-parallax-framer-motion-guide
*/
export const Parallax = ({ children, offset = 60 }: ParallaxProps) => {
export const Parallax = ({ children, offset }: ParallaxProps) => {
const prefersReducedMotion = useReducedMotion();

const { scrollY } = useScroll();
const [elementTop, setElementTop] = useState(0);
const [clientHeight, setClientHeight] = useState(0);
const ref = useRef<HTMLDivElement>(null);

useLayoutEffect(() => {
const element = ref.current;
const onResize = () => {
const topOfElement = (element?.getBoundingClientRect()?.top ?? 0) + window.scrollY;
setElementTop(topOfElement);
setClientHeight(window.innerHeight);
};
onResize();
window.addEventListener('resize', onResize);
return () => window.removeEventListener('resize', onResize);
}, [ref]);

const initial = elementTop - clientHeight;
const final = elementTop + offset;

const yRange = useTransform(scrollY, [initial, final], [offset, -offset]);
const { scrollYProgress } = useScroll({
target: ref,
// This mean aniimation starts when the top of the image touches the bottom of the viewport,
// and ends when the bottom of the image touches the top of the viewport.
offset: ['start end', 'end start'],
});
const yRange = useTransform(scrollYProgress, [0, 1], [offset, -offset]);
const y = useSpring(yRange, { stiffness: 200, damping: 30 });

if (prefersReducedMotion) {
return <>{children}</>;
}
const conditionalY = prefersReducedMotion ? 0 : y;

return (
<m.div ref={ref} style={{ y }}>
<m.div ref={ref} style={{ y: conditionalY }}>
{children}
</m.div>
);
Expand Down
2 changes: 1 addition & 1 deletion components/VerticalPoster/VerticalPoster.styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,5 +60,5 @@ export const parallaxBgImage = (prefersReducedMotion: boolean) => cnb('relative
});
export const parallaxForegroundWrapper = 'absolute top-0 right-0 z-10';
export const parallaxImage = (prefersReducedMotion: boolean) => cnb('relative size-full object-cover', {
'mt-[7%] lg:mt-[3vw]': !prefersReducedMotion,
//'mt-[7%] lg:mt-[3vw]': !prefersReducedMotion,
});

0 comments on commit 02c20d4

Please sign in to comment.