-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(ui/hooks): useSize hook 추가 (#305)
- Loading branch information
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
import { useState } from 'react'; | ||
import { useLayoutEffect } from './use-layout-effect'; | ||
|
||
export function useSize(element: HTMLElement | null) { | ||
const [size, setSize] = useState< | ||
{ width: number; height: number } | undefined | ||
>(); | ||
|
||
useLayoutEffect(() => { | ||
if (element) { | ||
setSize({ width: element.offsetWidth, height: element.offsetHeight }); | ||
|
||
const resizeObserver = new ResizeObserver((entries) => { | ||
if (!Array.isArray(entries)) { | ||
return; | ||
} | ||
|
||
if (!entries.length) { | ||
return; | ||
} | ||
|
||
const entry = entries[0] as ResizeObserverEntry; | ||
let width: number; | ||
let height: number; | ||
|
||
if ('borderBoxSize' in entry) { | ||
const borderBoxSizeEntry = entry.borderBoxSize; | ||
const borderSize = ( | ||
Array.isArray(borderBoxSizeEntry) | ||
? borderBoxSizeEntry[0] | ||
: borderBoxSizeEntry | ||
) as ResizeObserverSize; | ||
|
||
width = borderSize.inlineSize; | ||
height = borderSize.blockSize; | ||
} else { | ||
width = element.offsetWidth; | ||
height = element.offsetHeight; | ||
} | ||
|
||
setSize({ width, height }); | ||
}); | ||
|
||
resizeObserver.observe(element); | ||
|
||
return () => { | ||
resizeObserver.unobserve(element); | ||
}; | ||
} else { | ||
setSize(undefined); | ||
} | ||
}, [element]); | ||
|
||
return size; | ||
} |