How I implemented the Freshworks widget in a React / Next app

I have a file called useFreshDeskWidget.tsx:

import { useEffect } from 'react';

declare global {
    interface Window {
      fwSettings?: {
        widget_id: number;
      };
      FreshworksWidget?: {
        (...args: any[]): void;
        q?: any[];
      };
    }
  }

const useFreshDeskWidget = (widgetId: number) => {
  useEffect(() => {
    // Set widget settings
    window.fwSettings = { 'widget_id': widgetId };

    // Create FreshworksWidget function if it doesn't exist
    if (typeof window.FreshworksWidget !== 'function') {
      const n = function() {
        n.q.push(arguments);
      } as any;
      n.q = [];
      window.FreshworksWidget = n;
    }

    // Load the FreshDesk script
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = `https://widget.freshworks.com/widgets/${widgetId}.js`;
    script.async = true;
    script.defer = true;
    document.head.appendChild(script);

    // Cleanup script when component is unmounted
    return () => {
      document.head.removeChild(script);
      delete window.fwSettings;
      delete window.FreshworksWidget;
    };
  }, [widgetId]);
};

export default useFreshDeskWidget;

In my application, use my assigned widget ID to enable the widget on my page:

  useFreshDeskWidget(154000001780);

It’s as easy as that!

1 Like