DEV Community

Cover image for JAMstack comments
Sergey Todyshev
Sergey Todyshev

Posted on

JAMstack comments

My site is a Jamstack site. It is built using GatsbyJS powered by ReactJS. In this post I gonna show how you can add a free comments to your site with the following pretty simple steps.

  1. Use Reddit as a service that stores comments.
  2. Implement React component that shows reddit Comments.
  3. Integrate component to the blog post template

React Component

We gonna use NextJS useSWR hook to fetch comments from reddit re-post.
Here a code snippet of this component.

import React from 'react';
import useSWR from 'swr';
import moment from 'moment'; // to render relative time of the comment
import ContentLoader from 'react-content-loader'; // to render nice loader

export default function RedditComments({ reddit }) {
  if (!reddit) {
    return null;
  }
  const { data, error } = useSWR(reddit, fetcher);
  if (error) {
    // TODO render error
    return null;
  }
  const comments = data ? (
    data.map((item, i) => <Comment key={i} data={item.data} level={0} />)
  ) : (
    <Loader />
  );
  return (
    <div className="reddit">
      <a className="heading" href={reddit} target="_blank">
        Comments
      </a>
      {comments}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

The full source code is available here.

Component Integration

I've added a reddit metadata to each post having a reddit re-post.
After that I've extended a blog post template to render comment block.

// ...
import Reddit from '../components/Reddit';

const BlogPostTemplate = ({ pageContext }) => {
  let {
    // ...
    // new metadata
    reddit,
  } = pageContext;

  // ... computing more state like translations

  return (
      <Layout>
        {/* main content is omitted */}
        <footer>
            <Reddit reddit={reddit}/>
            {/* other footer blocks */}
        </footer>
      </Layout>
  );
};
Enter fullscreen mode Exit fullscreen mode

And voila it amazingly works.

Enjoy! EOF 😄

Link to original post

Top comments (0)