diff --git a/apps/scandic-web/components/SitewideAlert/index.tsx b/apps/scandic-web/components/SitewideAlert/index.tsx index b4adc20f7..179e2e21b 100644 --- a/apps/scandic-web/components/SitewideAlert/index.tsx +++ b/apps/scandic-web/components/SitewideAlert/index.tsx @@ -1,6 +1,6 @@ "use client" -import { useCallback, useEffect, useRef } from "react" +import { useCallback, useRef } from "react" import { trpc } from "@/lib/trpc/client" import { StickyElementNameEnum } from "@/stores/sticky-position" @@ -31,40 +31,36 @@ export default function SiteWideAlert() { name: StickyElementNameEnum.SITEWIDE_ALERT, }) - const updateHeight = useCallback(() => { - if (alertRef.current) { - const height = alertRef.current.offsetHeight + const updateHeightRefCallback = useCallback( + (node: HTMLDivElement | null) => { + if (node) { + const debouncedUpdate = debounce(([entry]) => { + const height = entry.contentRect.height - document.documentElement.style.setProperty( - "--sitewide-alert-height", - `${height}px` - ) + document.documentElement.style.setProperty( + "--sitewide-alert-height", + `${height}px` + ) - document.documentElement.style.setProperty( - "--sitewide-alert-sticky-height", - isAlarm ? `${height}px` : "0px" - ) - } - }, [isAlarm]) + document.documentElement.style.setProperty( + "--sitewide-alert-sticky-height", + isAlarm ? `${height}px` : "0px" + ) + }, 100) - useEffect(() => { - const alertElement = alertRef.current - const debouncedResizeHandler = debounce(() => { - updateHeight() - }, 100) - const observer = new ResizeObserver(debouncedResizeHandler) + const observer = new ResizeObserver(debouncedUpdate) + observer.observe(node) - if (alertElement) { - observer.observe(alertElement) - } - - return () => { - if (alertElement) { - observer.unobserve(alertElement) + return () => { + if (node) { + observer.unobserve(node) + } + observer.disconnect() + } } - observer.disconnect() - } - }, [updateHeight]) + }, + [isAlarm] + ) if (isLoading || !alert) { return null @@ -73,7 +69,10 @@ export default function SiteWideAlert() { return (
{ + updateHeightRefCallback(node) + alertRef.current = node + }} className={`${styles.sitewideAlert} ${isAlarm ? styles.alarm : ""}`} >