Display Reading Time for Gatsby Blog Posts Using gatsby-transformer-remark

Monica Powell
InstructorMonica Powell

Share this video with your friends

Send Tweet
Published a year ago
Updated 10 months ago

When maintaining a blog in Gatsby you might want to give readers heads up of approximately how much time is required to read a post. This lesson will walk through how to get the estimated reading time for each post. We'll examine the Gatsby GraphQL playground to see what data is available from gatsby-transformer-remark and write a GraphQL query to retrieve the estimated reading time for a given post.

Monica Powell: [0:01] We are currently running our Gatsby starter blog locally at localhost:8000 and looking at our blog index. In particular, we have this page query that we're using to populate our blog index.

[0:16] If we look at localhost:8000, you can see what the log index page looks like, and that is generated by the results of this query. You'll see that the posts are getting pulled from allMarkdownRemark. For each post, it is a node within edges, and you can see metadata about the actual article.

[0:39] If you start typing within the node, you can see what fields are available. I had just started typing timeToRead and that populated, but there's a bunch of other fields which you can explore within the GraphQL schema.

[0:54] Once I run this new query, you'll see that this is now returning timeToRead, which is an integer representing how long an article will take to read.

[1:08] We can update our page query to return the timeToRead. We now have that available for every single node that we're looking at. We can access that timeToRead value. I am now updating the markup within the JSX, so that we can display that information to users.

[1:42] You'll notice now that there is this TypeScript error because it's not expecting the data to return timeToRead. We can go up to the type for our data and update it, so that timeToRead is expected to be a number.

[2:02] If we go back into our website, we'll see that we have the time to read listed next to the date for every single article. I would want to go back and update this to have this min., so that it just is easier for a user to contextualize what this number means.

[2:26] To summarize, we've updated the page query to include a timeToRead for each node or article. When we're mapping through each of the nodes here, we destructured the timeToRead so that we have access to that data and then we added to the JSX a string that uses the timeToRead and displays that.

[2:51] Finally, we updated the type of data in order to know that timeToRead should be returned by the data and avoid having any type errors.