javascriptreactjsundefinedgatsbycalendly

window.Calendly.initInlineWidget is not defined on first load but works after refresh with useEffect in React and Gatsby


I am using Gatsby with React and am trying to implement a Calendly booking system. It sort of works. The issue is on first load it gives me the error

TypeError: Cannot read property 'initInlineWidget' of undefined

seen here

error

If I refresh the page the Calendly Object loads and renders just fine.

I am wondering if there is something I can do in the useEffect to avoid this issue.


    import React, { useEffect } from "react"
    import Layout from "../components/layout"
    
    const Calendly = styled.div`
      height: 800px;
      margin-top: 100px;
    `
    
    const IndexPage = ({ data }) => {
      useEffect(() => {
        window.Calendly.initInlineWidget({
          url: "https://calendly.com/absolute-hardwood",
          parentElement: document.getElementById("bookingjs"),
          prefill: {},
          utm: {},
        })
      }, [])
    
      return (
        <Layout>
          <Calendly id="bookingjs" />
        </Layout>
      )
    }
    
    export default IndexPage

Here is how I am adding the Calendly script in my gatsby-confing.js

    {
      resolve: "gatsby-plugin-load-script",
      options: {
        src: "https://assets.calendly.com/assets/external/widget.js",
      },
    }

Solution

  • Marshall here from Calendly. Since you are using React and Gatsby, you can use the react-calendly package to load the inline embed on your site.

    You will need to install the react-calendly package in your project, and then import the InlineWidget like this at the top of your file:

    import { InlineWidget } from "react-calendly";
    

    Then, you can use the component on your page:

    <InlineWidget url="https://calendly.com/your_scheduling_page" />
    

    I hope this helps! Further documentation can be found in the package readme on Github.