DEV Community

LocTran016
LocTran016

Posted on

Add utteranc.es to Gatsby (React)

Excuse me, I'm using Gatsby (React) and I'm trying my hard to add dark/light mode toggleable utturanc.es. My idea is that dark/light mode change, the state of utturancesComments will be updated and make it re-render but I haven't been succeed yet. Anyone could help me. Thanks

import React, { Component } from 'react';
import PropTypes from 'prop-types';

export class Comments extends Component {
  constructor(props) {
    super(props);
    this.commentBox = React.createRef();
  }
  componentDidMount() {
    const scriptEl = document.createElement('script');
    scriptEl.async = true;
    scriptEl.src = 'https://utteranc.es/client.js';
    scriptEl.setAttribute('crossorigin', 'anonymous');
    scriptEl.setAttribute('repo', 'loctran016/comments');
    scriptEl.setAttribute('issue-term', 'title');
    scriptEl.setAttribute('id', 'utterance');
    scriptEl.setAttribute('theme', this.props.theme);
    scriptEl.setAttribute('label', 'Comments :tada: :tada: :tada:');
    this.commentBox.current.appendChild(scriptEl);
  }
  render() {
    return (
      <div id="comments">
        <h2 className="my-0">
          Comments
        </h2>
        <div ref={this.commentBox} className="comment-box" />
      </div>
    );
  }
}

Comments.propTypes = {
  theme: PropTypes.string.isRequired
}

export class utturancesComments extends Component {
  constructor(props) {
    super(props);
    if (typeof(document.getElementById("dark")) != 'undefined' && document.getElementById("dark") != null) {
      return this.state = {
        isDarkTheme: true
      }
    }
    else {
      return this.state = {theme:'icy-dark'}
    }
  }
  render () {
    const isDarkMode = typeof(document.getElementById("dark")) != 'undefined' && document.getElementById("dark") != null
    let uTheme;
    if (isDarkMode) {
      uTheme = 'icy-dark'
    }
    else {
      uTheme = 'github-light'
    }
    return (<Comments theme={uTheme} />)
  }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
loctran016 profile image
LocTran016

Btw, here is my code for dark/light mode button:

export const ModeToggle = ({ ...props }) => {
  const [colorMode, setColorMode] = useColorMode()
  const [utterancesId] = useColorMode() ? 'light-utterance' : 'dark-utterance'
  return (
    <button
      variant="button.icon"
      className="mode-toggle"
      aria-label="Toggle mode"
      id={colorMode === "default" ? "light" : "dark"}
      onClick={() => {
        setColorMode(colorMode === "default" ? "dark" : "default");
      }}
      ml={[2, 4]}
      {...props}
      _hover={{
        color: "primary",
      }}
      _focus={{
        color: "text",
      }}
    >
      <Icon name={colorMode === "default" ? "sun" : "moon"} size="6" />
    </button>
  )
}
Enter fullscreen mode Exit fullscreen mode