@react-hook/size
Version:
A React hook for measuring the size of HTML elements including when they change
1 lines • 2.21 kB
Source Map (JSON)
{"version":3,"file":"index.mjs","sources":["../../src/index.tsx"],"sourcesContent":["import * as React from 'react'\nimport useResizeObserver from '@react-hook/resize-observer'\nimport useLayoutEffect from '@react-hook/passive-layout-effect'\n\n/**\n * A React hook for measuring the size of HTML elements including when they change\n *\n * @param target A React ref created by `useRef()` or an HTML element\n * @param options Configures the initial width and initial height of the hook's state\n */\nconst useSize = <T extends HTMLElement>(\n target: React.RefObject<T> | T | null,\n options?: UseSizeOptions\n): [number, number] => {\n const [size, setSize] = React.useState<[number, number]>(() => {\n const targetEl = target && 'current' in target ? target.current : target\n return targetEl\n ? [targetEl.offsetWidth, targetEl.offsetHeight]\n : [options?.initialWidth ?? 0, options?.initialHeight ?? 0]\n })\n\n useLayoutEffect(() => {\n const targetEl = target && 'current' in target ? target.current : target\n if (!targetEl) return\n setSize([targetEl.offsetWidth, targetEl.offsetHeight])\n }, [target])\n\n // Where the magic happens\n useResizeObserver(target, (entry) => {\n const target = entry.target as HTMLElement\n setSize([target.offsetWidth, target.offsetHeight])\n })\n\n return size\n}\n\nexport interface UseSizeOptions {\n // The initial width to set into state.\n // This is useful for SSR environments.\n initialWidth: number\n // The initial height to set into state.\n // This is useful for SSR environments.\n initialHeight: number\n}\n\nexport default useSize\n"],"names":["target","options","size","setSize","React","targetEl","current","offsetWidth","offsetHeight","initialWidth","initialHeight","useLayoutEffect","useResizeObserver","entry"],"mappings":"2IAUgB,CACdA,EACAC,SAEOC,EAAMC,GAAWC,EAAiC,aACjDC,EAAWL,GAAU,YAAaA,EAASA,EAAOM,QAAUN,SAC3DK,EACH,CAACA,EAASE,YAAaF,EAASG,cAChC,WAACP,MAAAA,SAAAA,EAASQ,4BAAgB,YAAGR,MAAAA,SAAAA,EAASS,6BAAiB,YAG7DC,EAAgB,SACRN,EAAWL,GAAU,YAAaA,EAASA,EAAOM,QAAUN,EAC7DK,GACLF,EAAQ,CAACE,EAASE,YAAaF,EAASG,gBACvC,CAACR,IAGJY,EAAkBZ,EAASa,QACnBb,EAASa,EAAMb,OACrBG,EAAQ,CAACH,EAAOO,YAAaP,EAAOQ,iBAG/BN"}