Skip to content

Instantly share code, notes, and snippets.

@prutya
Last active August 21, 2024 05:31
Show Gist options
  • Save prutya/f33974d4b764d38fd82f99e3ebda5ca3 to your computer and use it in GitHub Desktop.
Save prutya/f33974d4b764d38fd82f99e3ebda5ca3 to your computer and use it in GitHub Desktop.
A React component that adds Utterances (Comments widget built on top of GitHub Issues) to a page in Next.js
// See https://utteranc.es
"use client";
import { useRef, useEffect } from "react";
const UTTERANCES_SRC = "https://utteranc.es/client.js";
const UTTERANCES_ENABLED = process.env.NEXT_PUBLIC_UTTERANCES_ENABLED === "1";
const UTTERANCES_REPO = process.env.NEXT_PUBLIC_UTTERANCES_REPO;
const UTTERANCES_ISSUE_TERM = process.env.NEXT_PUBLIC_UTTERANCES_ISSUE_TERM;
const UTTERANCES_LABEL = process.env.NEXT_PUBLIC_UTTERANCES_LABEL;
const UTTERANCES_THEME = process.env.NEXT_PUBLIC_UTTERANCES_THEME;
export default function Comments() {
const containerRef = useRef(null);
const isLoaded = useRef(false);
useEffect(() => {
if (!UTTERANCES_ENABLED) {
return;
}
if (isLoaded.current) {
return;
}
const scriptElement = document.createElement("script");
scriptElement.async = true;
scriptElement.crossOrigin = "anonymous";
scriptElement.src = UTTERANCES_SRC;
scriptElement.setAttribute("repo", UTTERANCES_REPO);
scriptElement.setAttribute("issue-term", UTTERANCES_ISSUE_TERM);
scriptElement.setAttribute("label", UTTERANCES_LABEL);
scriptElement.setAttribute("theme", UTTERANCES_THEME);
containerRef.current?.replaceChildren(scriptElement);
isLoaded.current = true;
}, [isLoaded]);
return (
<div ref={containerRef}>
<p>
{UTTERANCES_ENABLED
? "Please enable JavaScript to use comments 🫥"
: "Comments are disabled"}
</p>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment