skip to Main Content

I am using @headlessui/react and want to send a google event to the datalayer when one of my Accordion Disclosure components is in the open position. How can I trigger a function to run when it is opened?

<Disclosure>
        {({ open }) => (
          <>
            <Disclosure.Button
              className={...  }
            >
              NAME
            </Disclosure.Button>
            <Transition
              show={open}
              ref={ref}
              className="..."
              enter="..."
              enterFrom="m..."
              beforeEnter={setHeight}
              leave="m..."
              beforeLeave={() => {
                if (ref.current) ref.current.style.maxHeight = '0px'
              }}
            >
              <Disclosure.Panel>
                <div
                  className={...}
                >
                PANEL CONTENT
                </div>
              </Disclosure.Panel>
            </Transition>
          </>
        )}
      </Disclosure>

2

Answers


  1. Chosen as BEST ANSWER

    Ah you can put a return statement inside the function and add commands above.

     <Disclosure>
            {({ open }) => {
    
              DO WHATEVER YOU WANT
    
              return (
                <>
                  <Disclosure.Button
    

  2. To trigger a function when your Accordion Disclosure component is opened using @headlessui/react, you can leverage the open state provided by the Disclosure component to call your function when it becomes true. In your case, you can send a Google Analytics event when the Accordion Disclosure is opened.

    Here’s an example of how you can achieve this:

    import { Disclosure } from "@headlessui/react";
    import { useEffect } from "react";
    
    // Your component...
    
    <Disclosure>
      {({ open }) => (
        <>
          <Disclosure.Button
            className={/* your button styles */}
          >
            NAME
          </Disclosure.Button>
          <Transition
            show={open}
            /* other transition props */
          >
            <Disclosure.Panel>
              <div className={/* your panel styles */}>
                PANEL CONTENT
              </div>
            </Disclosure.Panel>
          </Transition>
        </>
      )}
    </Disclosure>
    
    // Function to send a Google Analytics event when the Accordion is opened
    useEffect(() => {
      if (open) {
        // Replace with your Google Analytics event tracking code
        // For example, using gtag.js
        window.gtag("event", "Accordion Opened", {
          event_category: "Accordion Interaction",
          event_label: "Your label here",
        });
      }
    }, [open]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search