BLOG // May 6, 2021

Integrate Commento.io Comments with Gatsby

Commento is a lightweight, privacy-first comments system (think Disqus but 15KB in size), and it's the one powering comments on this blog.

After doing some research I decided it was the best option for my Gatsby based blog, and have written a small script to use it with Gatsby.

The Code

Copy the below file to src/components/commento.js

import React, { useEffect } from "react"

// Helper to add scripts to our page
const insertScript = (src, id, parentElement) => {
  const script = window.document.createElement("script")
  script.async = true
  script.src = src
  script.id = id
  parentElement.appendChild(script)
  return script
}

// Helper to remove scripts from our page
const removeScript = (id, parentElement) => {
  const script = window.document.getElementById(id)
  if (script) {
    parentElement.removeChild(script)
  }
}

// The actual component
const Commento = ({ id }) => {
  useEffect(() => {
    if (!window) {
      return
    }

    const document = window.document

    // In case our #commento container exists we can add our commento script
    if (document.getElementById("commento")) {
      insertScript(
        `https://cdn.commento.io/js/commento.js`,
        `commento-script`,
        document.body
      )
    }

    // Cleanup; remove the script from the page
    return () => removeScript(`commento-script`, document.body)
  }, [id])
  return <div id={`commento`} />
}

export default Commento

Then to embed it in your blog add the following import to the top of your blog file:

import Commento from "../components/commento"

And add this to wherever you want to display the comments:

<Commento id={data.strapiArticles.id} />

The ID field is optional but recommended, pass it a value that's unique to your post for the comments to be bound to. You can see I pass the the ID of my article.

Comments

Subscribe to new articles

If you enjoy my content, consider subscribing. You will only receive new blog stories, no other email.

Work

Site

© 2022 Dave Blakey. All rights reserved.

Development, startup and tech tips from Gatsby to Laravel, Strapi to PHP.