From 3ab5e39cf1153d5879a7ae2842b56ae5bfc5469c Mon Sep 17 00:00:00 2001 From: sirineJ <112706079+sirineJ@users.noreply.github.com> Date: Fri, 10 Jan 2025 16:26:47 +0100 Subject: [PATCH] Fix useScrollLock instances issue (#2860) * fix instances issue * add changeset --- .changeset/poor-ads-hunt.md | 5 +++++ .../hooks/useScrollLock/useScrollLock.ts | 19 +++++++++++++++---- 2 files changed, 20 insertions(+), 4 deletions(-) create mode 100644 .changeset/poor-ads-hunt.md diff --git a/.changeset/poor-ads-hunt.md b/.changeset/poor-ads-hunt.md new file mode 100644 index 0000000000..ce413e6778 --- /dev/null +++ b/.changeset/poor-ads-hunt.md @@ -0,0 +1,5 @@ +--- +"@sumup-oss/circuit-ui": patch +--- + +Fixed an issue with simultaneous instances of the `useScrollLock` hook. diff --git a/packages/circuit-ui/hooks/useScrollLock/useScrollLock.ts b/packages/circuit-ui/hooks/useScrollLock/useScrollLock.ts index 003c087178..a8c4558c32 100644 --- a/packages/circuit-ui/hooks/useScrollLock/useScrollLock.ts +++ b/packages/circuit-ui/hooks/useScrollLock/useScrollLock.ts @@ -15,6 +15,8 @@ import { useCallback, useEffect, useRef } from 'react'; +let instanceCount = 0; + export const useScrollLock = (isLocked: boolean): void => { const scrollValue = useRef(); @@ -27,6 +29,18 @@ export const useScrollLock = (isLocked: boolean): void => { body.style.width = ''; window.scrollTo(0, Number.parseInt(scrollY || '0', 10) * -1); }, []); + + useEffect(() => { + instanceCount += 1; + + return () => { + instanceCount -= 1; + if (instanceCount === 0) { + restoreScroll(); + } + }; + }, [restoreScroll]); + useEffect(() => { if (isLocked) { scrollValue.current = `${window.scrollY}px`; @@ -39,11 +53,8 @@ export const useScrollLock = (isLocked: boolean): void => { body.style.position = 'fixed'; body.style.width = `${bodyWidth}px`; body.style.top = `-${scrollY}`; - } else { + } else if (instanceCount === 1) { restoreScroll(); } - return () => { - restoreScroll(); - }; }, [isLocked, restoreScroll]); };