Knowledge for the World

How to use Disqus with your Gatsby site

Let's Disqus the benefits of React
  • by Zach (152)
  • Time to complete: 4 minutes

The normal Disqus installation methods don't work well in React since state changes can cause your comments area to re-render, clearing everything out. Additionally, the SSR nature of Gatsby can cause issues when the window object gets involved.

This short guide will show you how to implement Disqus in Gatsby so that you can show your Disqus comments area on your Gatsby site!

1

After stopping gatsby develop, install the react-disqus-comments library from NPM:

npm install react-disqus-comments

Then, restart your Gatsby site:

gatsby develop
2

I recommend creating some sort of Disqus.jsx or Comment.jsx wrapper component in case you decide to display your comments section in multiple places. Or, you can import directly into a page.

In either case, import the react-disqus-comments library into your page or component:

import ReactDisqusComments from 'react-disqus-comments';
3

In the render method of your page or component, load Disqus:

<ReactDisqusComments
    shortname="your_short_name"
    identifier={post.id}
    title={post.title}
    url={post.url}
    category_id={post.category_id}
/>

Specify your Disqus short name and other desired props to render the comments widget. shortname is the only required prop, but I recommend using the others to make it easier to manage your Disqus thread in the future.

In this example, you can see that Disqus short name is a string and all other props are dynamic variables based on the post itself.

4

This library provides some neat callback methods so that you can do dynamic things when comments are posted. For example, if you wanted to alert a user that a new comment was posted:

<ReactDisqusComments
    shortname="your_short_name"
    identifier={post.id}
    title={post.title}
    url={post.url}
    category_id={post.category_id}
    onNewComment={() => alert('new comment available!'}
/>
5

To lazy-load the widget in Gatsby/React, you can use the react-lazy-load library:

import LazyLoad from 'react-lazy-load';

...

<LazyLoad offsetTop={400}>
    <ReactDisqusComments
        shortname="your_short_name"
        identifier={post.id}
        title={post.title}
        url={post.url}
        category_id={post.category_id}
        onNewComment={this.notifyAboutComment}
    />
</LazyLoad>

This will initialize the comments section once it is scrolled to.

6

Questions? Comments?

Post in the [Disqus] comments section below and I'll do my best to help you out!