Creating a Gradient Reading Progress Bar in NextJS with TailwindCSS
I am building this portfolio website to showcase my app and services to the world. During my research on portfolio blog sites, I came across a reading progress bar that is placed at the top of the page to indicate how much of the post is left to read.
This progress bar is a good way to know how much content is remaining and it provides feedback to the user, potentially improving the user experience of the website.
I found a tutorial by Anshuman Bhardwaj that explains how to implement a reading progress bar in a React and TailwindCSS project. Since my site is built with NextJS and TailwindCSS, I was able to adapt the tutorial to suit my website.
Let's see how to create a reading progress bar like the one on my website.
Getting Started
If you want to access the full source code for this project, you can find it on the tutorial's below source code section.
Create a Hook File in Your NextJS Project
Copy this code snippet below and save it as useReadingProgressbar.ts file.
Code snippet
typescript
1import{ useEffect, useState }from"react";2import{ useRouter }from"next/router";34/**
5 * React Hook to get the scroll percentage from the page, returns value from 0 to 100
6 */7exportfunctionuseReadingProgress(){8const[completion, setCompletion]=useState(0);9const router =useRouter();1011useEffect(()=>{12functionupdateScrollCompletion(){13// see how much we have scrolled14const currentProgress = window.scrollY;15// see how much total scroll is available16const scrollHeight = document.body.scrollHeight - window.innerHeight;17if(scrollHeight){18setCompletion(19Number((currentProgress / scrollHeight).toFixed(2))*10020);21}22}2324functionhandleRouteChange(){25setCompletion(0);// Reset completion when the route changes26}2728// Add scroll and route change event listeners29 window.addEventListener("scroll", updateScrollCompletion);30 router.events.on("routeChangeStart", handleRouteChange);3132// Remove event listeners on unmount33return()=>{34 window.removeEventListener("scroll", updateScrollCompletion);35 router.events.off("routeChangeStart", handleRouteChange);36};37},[router]);3839return completion;40}
This code snippet was obtained from Anshuman Bhardwaj's blog post. I have added an additional NextJS router event to reset the completion to 0 when the page changes. This ensures that the reading progress bar will be updated when a user visits another blog post.
I have used a TailwindCSS gradient and adjusted the backgroundSize CSS property to reflect the completion percentage. This also supports the transition utility for smooth animations.