DEV Community

loading...

Discourse thread integration on a React Website

shahbaz17 profile image Mohammad Shahbaz Alam ・2 min read

Discourse is an open-source civilised discussion forum and used by many Developer communities. Mozilla, Magic, Netlify, Auth0, MongoDB to name a few.

This is a simple walkthrough integration of a discourse thread in a React application.

If you are an admin or a moderator of a discourse forum, I am pretty sure you have integrated the thread post onto your website's blog, guides, or product announcements page.

For others, who are not, discourse gives the below snippet:

<div id='discourse-comments'></div>

<script type="text/javascript">
  DiscourseEmbed = { discourseUrl: 'https://community.discourse.org/',
                     discourseEmbedUrl: 'REPLACE_ME' };

  (function() {
    var d = document.createElement('script'); d.type = 'text/javascript'; d.async = true;
    d.src = DiscourseEmbed.discourseUrl + 'javascripts/embed.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(d);
  })();
</script>
Enter fullscreen mode Exit fullscreen mode

This is straightforward, just paste the above snippet to the page where you want to integrate discourse thread comments.

React

Create a discourse-forum.js file and paste the below code

import { useEffect } from 'react';

export default function DiscourseForum() {
  useEffect(() => {
    window.DiscourseEmbed = {
      discourseUrl: 'https://community.discourse.org/',
      topicId: 123,
    };

    const d = document.createElement('script');
    d.type = 'text/javascript';
    d.async = true;
    d.src = window.DiscourseEmbed.discourseUrl + 'javascripts/embed.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(d);
  }, []);

  return (
    <div>
      <div id="discourse-comments"></div>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Replace discourseUrl with your community forum URL and topicId with the thread id from your community forum.

And make sure to go to the admin settings and click on Customise>Embedding>+Add Host and add https://www.website.com as the host.

Using DiscourseForum()

Import DiscourseForum to the page where you want to integrate the thread comments.

import DiscourseForum from '../link/to/the/file/discourse-forum.js';
Enter fullscreen mode Exit fullscreen mode

And use like this in your page

<DiscourseForum />
Enter fullscreen mode Exit fullscreen mode

You can further customise this as per your need.

Cheers!

Discussion (0)

pic
Editor guide