Snippet

Commento for React

src/components/Commento.js
import React, { useEffect, useState } from 'react'

const insertScript = src =>
    new Promise(resolve => {
        const script = window.document.createElement('script')

        script.async = true
        script.src = src
        script.id = 'commento-script'
        script.addEventListener('load', () => resolve(script))
        document.body.appendChild(script)
    })

const removeScript = id => {
    const script = window.document.getElementById(id)

    if (script) {
        document.body.removeChild(script)
    }
}

const Commento = ({ id, host = 'https://cdn.commento.io' }) => {
    const [isLoaded, setLoaded] = useState(false)

    useEffect(() => {
        if (!isLoaded) {
            insertScript(`${host}/js/commento.js`).then(() => setLoaded(true))
        }

        return () => removeScript('commento-script')
    }, [])

    return <div id="commento" />
}

export default Commento

Context

This blog's comments are powered by Commento. It's a great service privacy-wise, but they don't provide much help with its setup except for a vainilla script. With this component, you can easily add Commento to your own Gatsby (or React-powered) site.

Enjoyed the article? Consider sharing it on Twitter so others can enjoy it too :)

Share on Twitter

Receive project updates, article drafts & thoughts on your inbox every saturday.

Subscribe →