Skip to content

Commit

Permalink
feat: create useViewportSize hook (#933)
Browse files Browse the repository at this point in the history
  • Loading branch information
NikitaCG authored Aug 24, 2023
1 parent 5eab30f commit 637f88d
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import {act, fireEvent, renderHook} from '@testing-library/react';

import {useViewportSize} from '..';

test('Check useViewportSize correct work', () => {
const view = renderHook(() => useViewportSize());

act(() => {
window.innerHeight = 500;
window.innerWidth = 500;
});

fireEvent(window, new Event('resize'));

expect(view.result.current).toEqual({height: 500, width: 500});

act(() => {
window.innerHeight = 1200;
window.innerWidth = 1200;
});

fireEvent(window, new Event('resize'));

expect(view.result.current).toEqual({height: 1200, width: 1200});
});
2 changes: 2 additions & 0 deletions src/components/utils/useViewportSize/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export {useViewportSize} from './useViewportSize';
export type {ViewportSize} from './useViewportSize';
38 changes: 38 additions & 0 deletions src/components/utils/useViewportSize/useViewportSize.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import React from 'react';

export interface ViewportSize {
width?: number;
height?: number;
}

const getViewportSize = (): ViewportSize => ({
width: window?.visualViewport?.width ?? window?.innerWidth ?? undefined,
height: window?.visualViewport?.height ?? window?.innerHeight ?? undefined,
});

/**
* A hook to get the size of the viewport when resizing
*
* @return - {width, height}
*/
export const useViewportSize = (): ViewportSize => {
const [size, setSize] = React.useState<ViewportSize>(getViewportSize());

React.useEffect(() => {
const onResize = () => {
let newSize = getViewportSize();
if (newSize.width === size?.width && newSize.height === size?.height) {
newSize = size;
}
setSize(newSize);
};

(window.visualViewport ?? window).addEventListener('resize', onResize);

return () => {
(window.visualViewport ?? window).removeEventListener('resize', onResize);
};
}, [size]);

return size;
};

0 comments on commit 637f88d

Please sign in to comment.