
Enhancing user experience with visual indicators is crucial in modern web applications. A scroll progress indicator provides a subtle yet effective way to show how much of the page the user has scrolled. In this guide, we’ll build a scroll progress bar using Framer Motion in a Next.js project.
Why Use Framer Motion?
Framer Motion is a powerful animation library for React that allows smooth animations with minimal effort. It makes handling scroll-based animations straightforward.
Setting Up the Scroll Progress Component
Here’s the complete ScrollProgress
component:
How It Works
- The
useScroll()
hook from Framer Motion tracks the vertical scroll progress of the page. - The
motion.div
is scaled horizontally (scaleX
) based onscrollYProgress
, creating a dynamic progress bar. - The component is positioned at the top of the page (
fixed inset-x-0 top-0 z-50
). - The
cn
function helps with conditional class names, ensuring flexibility.
Adding the Component to Your Next.js App
To use the ScrollProgress
component, import and include it in your layout or page component:
Styling the Progress Bar
The default class "scrollGrad"
can be defined in your global CSS file:
Conclusion
With just a few lines of code, we’ve implemented a smooth and responsive scroll progress indicator using Framer Motion. This feature improves user engagement and provides visual feedback. Try integrating it into your project today!
Happy coding! 🚀