Calendly Embedding Issues in Next.js Project: TypeError and Other Errors

274 views Asked by At

I'm facing issues while trying to embed Calendly in my Next.js 13.5 project. I have tried two different approaches, but both have resulted in errors. I hope someone can help me figure out what's going wrong.

Issue 1: Using Calendly's Script

I initially attempted to embed Calendly using their official script, as shown in the code below:

"use client";
import Head from "next/head";
import React, { useEffect } from "react";

export default function Calendly() {
  useEffect(() => {
    window.Calendly.initInlineWidget({
      url: "url here ",
      parentElement: document.getElementById("calendly-inline-widget"),
    });
  });
  return (
    <>
      <Head>
        <script
          src="https://assets.calendly.com/assets/external/widget.js"
          type="text/javascript"
          async
        ></script>
      </Head>
      <div
        id="calendly-inline-widget"
        style={{ minWidth: 320, height: 580 }}
        data-auto-load="false"
      ></div>
    </>
  );
}

However, I encountered the following error:

TypeError: Cannot read properties of undefined (reading 'initInlineWidget')

Issue 2: Using react-calendly

As an alternative, I tried using the react-calendly library, but I encountered the following error:

Error: Object prototype may only be an Object or null: undefined

I have been stuck on these issues for a while and would appreciate any guidance or insights on how to successfully embed Calendly in my Next.js project. If you need any additional information or code snippets, please let me know.

Thank you in advance for your help!

1

There are 1 answers

0
Fabio Nettis On

To load a third-party script for multiple routes, import next/script and include the script directly in your layout component, you can find more about this component here. As you can see I use the onLoad method instead of a useEffect like in your example, this is callback is only ever invoked once, when the script has loaded.

import Script from "next/script";

export default async function Layout(): Promise<JSX.Element> {
  return (
    <>
      <Script
        async
        type="text/javascript"
        src="https://assets.calendly.com/assets/external/widget.js"
        onLoad={() => {
          console.log("Script has loaded");
        }}
      />

      <div
        data-auto-load="false"
        id="calendly-inline-widget"
        style={{ minWidth: 320, height: 580 }}
      />
    </>
  );
}

Nice to know: Next.js will ensure the script will only load once, even if a user navigates between multiple routes in the same layout.


From what I have seen there is also a NPM package called react-calendly, maybe worth giving that a shot if everything else fails.