Search code examples
reactjsdocusaurus

Docusaurus wrapper component renders incorrectly when tag filter is used


I have created a wrapper 'BlogPostItemWrapper' to wrap the 'BlogPostItem' component with GisCus as below. It generally works fine, i.e. if I open a list of my all articles in '/blog' the '/GiscusComponent' is not loaded but if I open one article the 'GiscusComponent' is loaded. So far so good. As soon as I filter articles with tags, I see the comment input dialog, which is not supposed to be loaded, no clue why!? See screenshot-1.

import React from 'react';
import { useBlogPost } from '@docusaurus/theme-common/internal'
import BlogPostItem from '@theme-original/BlogPostItem';
import GiscusComponent from '@site/src/components/GiscusComponent';
import useIsBrowser from '@docusaurus/useIsBrowser';

export default function BlogPostItemWrapper(props) {
  const { metadata } = useBlogPost()
  const isBrowser = useIsBrowser();

  const { frontMatter, slug, title } = metadata
  const { enableComments } = frontMatter

  // Workaround from https://docusaurus.io/docs/advanced/ssg for the Error 'ReferenceError: window is not defined' during the build
  var isCurrentUrlBlog = false
  if (isBrowser) {
    isCurrentUrlBlog = window.location.pathname === "/blog"
  }

  return (
    <>
      <BlogPostItem {...props} />
      {(enableComments && !isCurrentUrlBlog) && (
        <GiscusComponent />
      )}
    </>
  );
}

Screenshot-1


Solution

  • Error Explanation - Your tags page is working as intended.You have handled the use case to not render the GisCus component when on /blog path but this is a kind of hack. If you ever swizzle the BlogTagsPostsPage, it renders the BlogPostItems but because you are not on the /blog path it renders the GisCus component too which is what you have in your uploaded screenshot.

    Solution - The useBlogPost hook also returns a property called isBlogPostPage. You can use this to only render the GisCusComponent when you are on the BlogPostPage(This component renders when you open an individual blog).

    import React from 'react';
    import { useBlogPost } from '@docusaurus/theme-common/internal'
    import BlogPostItem from '@theme-original/BlogPostItem';
    import GiscusComponent from '@site/src/components/GiscusComponent';
    
    
    export default function BlogPostItemWrapper(props) {
      const { metadata, isBlogPostPage } = useBlogPost()
      const isBrowser = useIsBrowser();
    
      const { frontMatter, slug, title } = metadata
      const { enableComments } = frontMatter
    
      
    
      return (
        <>
          <BlogPostItem {...props} />
          {(enableComments && isBlogPostPage) && (
            <GiscusComponent />
          )}
        </>
      );
    }