JavaScript Enthusiast | Software Developer | Open Source Contributor | Technical Speaker

How to Add Comments to a Gatsby Blog

Oct 16, 2022#Gatsby.js6 min read

What is Utterances?

Utterances is a lightweight comments system that uses the Issues feature of a GitHub repository to store the comment data. Every blog post is associated with an issue in the repository. And every time user comments something on your blog, the comment is added to that issue. If an issue doesn’t exist for a blog post, the Utterances bot will create a new issue when someone adds a comment to the blog post.

Adding Utterances to your blog

Before adding Utterances to your blog you need to create a new GitHub repository and install the Utterances app for the newly created repository.

Then you need to add the following script tag to your blog template and place it in the position where you want to display the comments widget.

  repo="[ENTER REPO HERE]"

But since Gatsby uses React.js, we won't be able to directly use the following script. Instead, we need to create a React Component that'll render this script tag for us.

import React, { useEffect } from "react"

const elementId = "my-comment-widget"

const Comments = () => {
  useEffect(() => {
    const script = document.createElement("script")
    const element = document.querySelector(`#${elementId}`)

    script.src = ""
    script.async = true
    script.setAttribute("repo", "[YOUR_REPO_NAME]")
    script.setAttribute("issue-term", "pathname")
    script.setAttribute("label", "comment :speech_balloon:")
    script.setAttribute("theme", "github-dark")
    script.setAttribute("crossorigin", "anonymous")


    return () => element.removeChild(element.firstChild)
  }, [])

  return <div id={elementId} />

export default Comments

Tip: Don’t forget to replace [YOUR_REPO_NAME] with your GitHub repository name. Here, you need to specify your GitHub username followed by the repository name. So, if your username is abc and your repository name is xyz you’ll assign abc/xyz to this attribute.

As you can see above component utilizes the useEffect hook to render the script. Now, all you need is to place the component inside your blog post template.

import * as React from "react"
import { Link, graphql } from "gatsby"
import Layout from "../components/layout"
import Seo from "../components/seo"
import PostInfo from "../components/post-info"
import Comments from "../components/comments"

const BlogPostTemplate = () => {
  return (
      <Comments />

export default BlogPostTemplate

And that's it!

In case you have any queries or questions feel free to drop a comment in the Utterances widget placed at the bottom of the screen. 😏