How To Add Comments To A Gatsby Blog

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 use the following script directly. Instead, we must create a React Component to 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, the component utilizes the useEffect hook to render the script. Now, you only need 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!

I hope you enjoyed this post. If you've any queries or feedback, feel free to drop a comment or reach out to me on Twitter @harshalslimaye.

Similar Articles