DEV Community

Cover image for How to Add Commento (or other Comments) to Gatsby
Keith Holliday
Keith Holliday

Posted on

How to Add Commento (or other Comments) to Gatsby

Recently, I wanted to add comments to by Gatsby site. I found this open source sysetem (Commento), although I did sign up for the paid version to support open source :D.

Original post here: https://koalatea.io/gatsby-add-comments/

Anyway, I wanted to add this to my site. After signing up, I was given the follow code snippet.

<script defer src="https://cdn.commento.io/js/commento.js"></script> <div id="commento"></div> 
Enter fullscreen mode Exit fullscreen mode

The system is supposed to automatically recognize the page and only pull comments for that. So, I just needed to add this to a page and it should work, however, that did not work for me.

This could be because of the caching I used on Gatsby, but I believe this is because of how React Handles it. To solve this, I created a Comment Component to manually inject the script.

import React, { useEffect } from 'react'; const Comments = () => { useEffect(() => { const script = document.createElement('script'); script.src = 'https://cdn.commento.io/js/commento.js'; script.async = true; const comments = document.getElementById('comments-container'); if (comments) comments.appendChild(script); }, []); return ( <> <div id="comments-container"></div>  <div id="commento"></div>  </>  ); }; export default Comments; 
Enter fullscreen mode Exit fullscreen mode

I have a file called post.jsx which is used as a template to render post. In that file I add the following, and comments are added to each page.

<Comments /> 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)