I have a scroll-based animation in a React component using Framer Motion. It animates a set of cards (motion.div
) as the user scrolls down. However, the issue I'm facing is that on certain desktop resolutions, the animation doesn't complete properly because there's not enough height to scroll fully.
Here's the working demo with code: .jsx
I'm currently using hardcoded breakpoints (THRESHOLDS.SNAP, THRESHOLDS.MOVE_UP, etc.) to trigger different animation states, but this approach isn't flexible enough for all screen sizes.
import { useMemo } from "react";
import { motion } from "framer-motion";
import { useSmoothScroll } from "./useSmoothScroll";
import { useViewport } from "./useViewport";
// Define the card data and animation constants
const CARDS = ["Consult.ai", "Translate.ai", "Read.ai", "Flip.ai"];
const THRESHOLDS = { MOVE_UP: 90, MOVE_LEFT: 250, SNAP: 330 };
const GAPS = { DESKTOP: 260, MOBILE: 180 };
const MOVEMENTS = {
MOVE_UP: CARDS.map((_, index) => -100 * (CARDS.length - 1 - index)),
MOVE_LEFT: [-100, -330, -550, -760],
MOVE_BOTTOM: [300, 200, 100, 0],
};
const SIZES = {
INITIAL: { width: "10rem", height: "16rem" },
EXPANDED: { width: "30rem", height: "45rem" },
};
export default function CardTransition() {
const scrollY = useSmoothScroll();
const { width: viewportWidth } = useViewport();
const animatedCards = useMemo(() => {
const gap = viewportWidth < 768 ? GAPS.MOBILE : GAPS.DESKTOP;
return CARDS.map((_, index) => {
const initialX = (index - (CARDS.length - 1) / 2) * gap;
const moveUp =
scrollY > THRESHOLDS.MOVE_UP ? MOVEMENTS.MOVE_UP[index] : 0;
let moveLeft =
scrollY > THRESHOLDS.MOVE_LEFT ? MOVEMENTS.MOVE_LEFT[index] : 0;
if (viewportWidth < 768) moveLeft /= 1.5;
const animate =
scrollY > THRESHOLDS.SNAP
? {
left: 0,
width: SIZES.EXPANDED.width,
height: SIZES.EXPANDED.height,
bottom: MOVEMENTS.MOVE_BOTTOM[index],
}
: { x: initialX + moveLeft, y: moveUp };
return { key: index, initialX, animate };
});
}, [scrollY, viewportWidth]);
return (
<div className="min-h-[140vh] w-full relative flex items-center justify-center bg-gray-100">
<div className="w-full h-full flex items-center justify-center">
{animatedCards.map(({ key, initialX, animate }) => (
<motion.div
key={key}
className="absolute bottom-60 w-40 h-64 bg-green-800 text-white flex items-center justify-center text-lg font-semibold shadow-lg rounded-xl"
style={{ zIndex: CARDS.length - key }}
initial={
scrollY > THRESHOLDS.SNAP ? { x: 0, y: 0 } : { x: initialX, y: 0 }
}
animate={animate}
transition={{ type: "spring", stiffness: 60, damping: 15 }}
>
{CARDS[key]}
</motion.div>
))}
</div>
</div>
);
}