add reading time to a next.js blogrespect your reader's time
minute read
We've all experienced it. You start reading an article, and something comes up. It's time to move onto the next task. But you didn't even get half way through the article. And depending on the content, maybe you didn't even make it far enough for any notable takeaways.
That's a waste of your time.
Sure you might come back to it, but is that as impactful as consuming the content top to bottom in one sitting? Probably not.
The solution is simple. Let users know how long it takes to read each post. And the implementation is just as straightforward. In the example below, I'll explain how I added reading time to my markdown blog, made with Next.js and Remark.
Words per minute
The average adult reads at a pace of about 200 to 250 words per minute. Although adults are the target audience, we still don't want to tailor the content exclusively to that reading level. When writing for a general audience, I recommend writing for a grade 7-9 reading level; a pace of about 150-200 words per minute. I want this feature to be as inclusive as possible, and we're often chatting about some pretty complex topics, so I'll default to using 150 words per minute in my calculations below.
Calculate reading time
Go to the page that you want to display the reading time on. In the example below, we'll modify the getStaticProps
function. This way we can ensure the reading time is pre-rendered at build time, and keeps your page speed snappy.
We first need to calculate the reading time for the post. You can do this by using something similar to the function below. Your implementation might differ slightly based on how you set up your post data, but the TL;DR is that you need to get the HTML you plan to use for the post content into a variable (postData.contentHtml
in the remark
example below) to further process.
export async function getStaticProps({ params }) {
// Post content converted from markdown to HTML with Remark
const postData = await getPostData(params.slug);
// Reading speed
const wordsPerMinute = 150;
// Count words, split by whitespace characters
const wordCount = postData.contentHtml.split(/\s+/).length;
// Divide the amount of words by the average words read per minute, and round the number up.
const readTime = Math.ceil(wordCount / wordsPerMinute);
// Pass the new read time alongside the post data as props to the page
return {
props: {
postData,
readTime,
},
};
}
Display reading time
Lastly, add the new readTime
prop to the Post
component. Then place it within the Post
component's JSX wherever you prefer.
// Add readTime to props
export default function Post({ postData, readTime }) {
return (
<>
{/* Add read time */}
<p>{readTime} minute read</p>
</>
);
}
With a only a few lines of code, this small change can have a big impact on your readers experience right away.