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
Ah you can put a return statement inside the function and add commands above.
To trigger a function when your
Accordion Disclosure
component is opened using@headlessui/react
, you can leverage theopen
state provided by theDisclosure
component to call your function when it becomestrue
. In your case, you can send a Google Analytics event when theAccordion Disclosure
is opened.Here’s an example of how you can achieve this: