Skip to content

Commit

Permalink
Fix(web-react): Cleanup scrolling when Modal is unmounted
Browse files Browse the repository at this point in the history
refs #DS-1126
  • Loading branch information
literat committed Jan 23, 2024
1 parent 8befaa8 commit 654a147
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
12 changes: 11 additions & 1 deletion packages/web-react/src/hooks/__tests__/useScrollControl.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { renderHook, act } from '@testing-library/react-hooks';
import { act, renderHook } from '@testing-library/react-hooks';
import { MutableRefObject } from 'react';
import { useScrollControl } from '../useScrollControl';

Expand Down Expand Up @@ -33,4 +33,14 @@ describe('useScrollControl', () => {

expect(document.body.classList.contains('is-scrolling-disabled')).toBe(false);
});

it('should clean up on unmount', () => {
const mockRef = createMockRef(true) as MutableRefObject<HTMLDialogElement | null>;

const { unmount } = renderHook(() => useScrollControl(mockRef, true));

unmount();

expect(document.body.classList.contains('is-scrolling-disabled')).toBe(false);
});
});
17 changes: 16 additions & 1 deletion packages/web-react/src/hooks/useScrollControl.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, MutableRefObject } from 'react';
import { MutableRefObject, useEffect } from 'react';

const CLASSNAME_SCROLLING_DISABLED = 'is-scrolling-disabled';

Expand All @@ -23,5 +23,20 @@ export const useScrollControl = (ref: MutableRefObject<HTMLDialogElement | null>
} else if (ref.current && !ref.current.open) {
enableScroll();
}

/**
* Cleanup scrolling when unmounting
*
* @see https://jira.lmc.cz/browse/DS-1126
*
* When the use of the Dialog in page is optimized by the condition like
* `isOpen && <Dialog />`, the Dialog component will be unmounted sooner
* than the Dialog is closed correctly and all side effects are fulfilled.
* In this case, the class and style attributes added to the body element
* will not be removed, and the page will be scrolled.
*/
return () => {
enableScroll();
};
}, [isOpen, ref]);
};

0 comments on commit 654a147

Please sign in to comment.