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.
- Use Reddit as a service that stores comments.
- Implement React component that shows reddit Comments.
- 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> ); }
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> ); };
And voila it amazingly works.
Enjoy! EOF 😄
Top comments (0)