Using the C2C Widget with React
install the package:
npm install @niravcodes/call-widget
then:
C2CWidgetInternal.tsx
import { useRef, useEffect } from "react";
import BrowserOnly from "@docusaurus/BrowserOnly";
export default function C2CWidgetInternal({
buttonId,
destination,
supportsVideo,
supportsAudio,
token,
}: {
buttonId: string;
destination: string;
supportsVideo: boolean;
supportsAudio: boolean;
token: string;
}) {
const rootRef = useRef<HTMLDivElement>(null);
useEffect(() => {
// In SSR settings, we import the widget dynamically in client side
// Otherwise, this import should be at the top of the file
import("@niravcodes/call-widget");
}, []);
// react doesn't like other scripts controlling the DOM,
// we create an empty div and inject things via js
// note: when component unmounts, we're clearing the div
// so react doesn't get confused and break things
useEffect(() => {
if (rootRef.current) {
rootRef.current.innerHTML = "";
const widget = document.createElement("c2c-widget");
widget.setAttribute("buttonId", buttonId);
widget.setAttribute(
"callDetails",
JSON.stringify({
destination,
supportsVideo,
supportsAudio,
}),
);
widget.setAttribute("token", token);
rootRef.current.appendChild(widget);
}
return () => {
if (rootRef.current) {
rootRef.current.innerHTML = "";
}
};
}, [buttonId, destination, supportsVideo, supportsAudio]);
return <BrowserOnly>{() => <div ref={rootRef} />}</BrowserOnly>;
}
Of course, you need to have a different component which creates a button with the buttonId
attribute. Eg:
C2CWidget.tsx
import React from "react";
import BrowserOnly from "@docusaurus/BrowserOnly";
import C2CWidgetInternal from "./C2CWidgetInternal";
import useIsBrowser from "@docusaurus/useIsBrowser";
import { useState } from "react";
export default function C2CWidget({
destination,
supportsVideo,
supportsAudio,
token,
children,
}: {
destination: string;
supportsVideo: boolean;
supportsAudio: boolean;
token: string;
children: React.ReactNode;
}) {
const isBrowser = useIsBrowser();
const [randomId, setRandomId] = useState(Math.random().toString(36).substring(2, 15));
if (!isBrowser) {
return null;
}
return (
<BrowserOnly>
{() => (
<>
<div
id={`callButton-${randomId}`}
className="demo-button-disabled"
style={{ flex: 1, transition: "opacity 0.4s ease-in-out" }}
>
{children}
</div>
<C2CWidgetInternal
buttonId={`callButton-${randomId}`}
destination={destination}
supportsVideo={supportsVideo}
supportsAudio={supportsAudio}
token={token}
/>
</>
)}
</BrowserOnly>
);
}