Sayed's Blog

Adding comments to a Gatsby blog using Commento

Posted August 12th, 2019

At the time of writing this post, I am using Gatsby to power my blog/site.

Gatsby is a static site generator that uses React. Using it enables me to make my website performant and cheap - I don't need a server since all of the content is static. I only need to pay for the domain.

To improve this website, I wanted to add comments to the blog. Because my website is static, I couldn't go for the traditional option of building the page with the comments loaded from a database whenever anyone requests the page.

After exploring a few options, I decided to go with Commento. Commento are a relatively cheap, lightweight commenting platform with an emphasis on platforms.

To get started, first I had to create a Commento account here. The next step involved registering my domain.

The final step is usually simple, but proved more difficult than I expected to integrate with React and Gatsby.

Usually adding two lines of code is enough for this to work:

<div id="commento"></div>
<script src="https://cdn.commento.io/js/commento.js"></script>

Unfortunately, that was not enough for it to work for me. This is because a script does not execute if I add it to a react component. To get it to work I had to wrap a Helmet component around it.

I created a component called 'Comments.js'

import { Helmet } from "react-helmet";
import React from "react"

export default class Comments extends React.Component {

    render() {
        return (
            <React.Fragment>
                <div id="commento"/>
                <Helmet>
                    <script 
                        defer 
                        src="https://cdn.commento.io/js/commento.js"
                        />
                </Helmet>
            </React.Fragment>
        );
    }
}

And included that in the blog template.

export default ({ data }) => {
    const post = data.markdownRemark
    return (
        <Layout>
            <SEO title={post.frontmatter.title} />
            <h1>{post.frontmatter.title}</h1>
            <h4>Posted {post.frontmatter.date}</h4>
            <div dangerouslySetInnerHTML={{__html: post.html}} />
            <Comments/>
        </Layout>
    )
}

Whilst there are still some issues due to react lifecycles working differently from the Commento lifecycle, this solved most of the problems.

PreviousNext