Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork43
A React hook that allows you to use a ResizeObserver to measure an element's size.
License
ZeeCoder/use-resize-observer
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
A React hook that allows you to use a ResizeObserver to measure an element's size.
- Written inTypeScript.
- Tiny:500B (minified, gzipped) Monitored bysize-limit.
- Exposes anonResize callback if you need more control.
- Works withSSR.
- Works withCSS-in-JS.
- Supports custom refs in case youhad one already.
- Uses RefCallback by default To address delayed mounts and changing ref elements.
- Ships a polyfilled version
- Handles many edge cases you might not even think of.(See this documentation and the test cases.)
- Throttle / Debounce
- Tested in real browsers (Currently latest Chrome, Safari, Firefox and IE 11, sponsored by BrowserStack)
yarn add use-resize-observer --dev# ornpm install use-resize-observer --save-devNote that the default builds are not polyfilled! For instructions and alternatives,see theTranspilation / Polyfilling section.
importReactfrom"react";importuseResizeObserverfrom"use-resize-observer";constApp=()=>{const{ ref, width=1, height=1}=useResizeObserver<HTMLDivElement>();return(<divref={ref}> Size:{width}x{height}</div>);};
Note that "ref" here is aRefCallback, not aRefObject, meaning you won't beable to access "ref.current" if you need the element itself.To get the raw element, either you use your own RefObject (see later in this doc)or you hook in the returned ref callback, like so:
importReact,{useCallback,useEffect,useRef}from"react";importuseResizeObserverfrom"use-resize-observer";constuseMergedCallbackRef=(...callbacks:Function[])=>{// Storing callbacks in a ref, so that we don't need to memoise them in// renders when using this hook.constcallbacksRegistry=useRef<Function[]>(callbacks);useEffect(()=>{callbacksRegistry.current=callbacks;},[...callbacks]);returnuseCallback((element)=>{callbacksRegistry.current.forEach((callback)=>callback(element));},[]);};constApp=()=>{const{ ref, width=1, height=1}=useResizeObserver<HTMLDivElement>();constmergedCallbackRef=useMergedCallbackRef(ref,(element:HTMLDivElement)=>{// Do whatever you want with the `element`.});return(<divref={mergedCallbackRef}> Size:{width}x{height}</div>);};
You can pass in your own ref instead of using the one provided.This can be useful if you already have a ref you want to measure.
constref=useRef<HTMLDivElement>(null);const{ width, height}=useResizeObserver<HTMLDivElement>({ ref});
You can even reuse the same hook instance to measure different elements:
There might be situations where you have an element already that you need to measure.ref now accepts elements as well, not just refs, which means that you can do this:
const{ width, height}=useResizeObserver<HTMLDivElement>({ref:divElement,});
The hook reacts to ref changes, as it resolves it to an element to observe.This means that you can freely change the customref option from one ref toanother and back, and the hook will start observing whatever is set in its options.
In certain cases you might want to delay creating a ResizeObserver instance.
You might provide a library, that only optionally provides observation featuresbased on props, which means that while you have the hook within your component,you might not want to actually initialise it.
Another example is that you might want to entirely opt out of initialising, whenyou run some tests, where the environment does not provide theResizeObserver.
You can do one of the following depending on your needs:
- Use the default
refRefCallback, or provide a custom ref conditionally,only when needed. The hook will not create a ResizeObserver instance up untilthere's something there to actually observe. - Patch the test environment, and make a polyfill available as the ResizeObserver.(This assumes you don't already use the polyfilled version, which would switchto the polyfill when no native implementation was available.)
By the default the hook will trigger a re-render on all changes to the targetelement's width and / or height.
You can opt out of this behaviour, by providing anonResize callback function,which'll simply receive the width and height of the element when it changes, sothat you can decide what to do with it:
importReactfrom"react";importuseResizeObserverfrom"use-resize-observer";constApp=()=>{// width / height will not be returned here when the onResize callback is presentconst{ ref}=useResizeObserver<HTMLDivElement>({onResize:({ width, height})=>{// do something here.},});return<divref={ref}/>;};
This callback also makes it possible to implement your own hooks that report onlywhat you need, for example:
- Reporting only width or height
- Throttle / debounce
- Wrap in
requestAnimationFrame
You might want to receive values less frequently than changes actually occur.
While this hook does not come with its own implementation of throttling / debouncing,you can use theonResize callback to implement your own version:
On initial mount the ResizeObserver will take a little time to report on theactual size.
Until the hook receives the first measurement, it returnsundefined for widthand height by default.
You can override this behaviour, which could be useful for SSR as well.
const{ ref, width=100, height=50}=useResizeObserver<HTMLDivElement>();
Here "width" and "height" will be 100 and 50 respectively, until theResizeObserver kicks in and reports the actual size.
If you only want real measurements (only values from the ResizeObserver withoutany default values), then you can just leave defaults off:
const{ ref, width, height}=useResizeObserver<HTMLDivElement>();
Here "width" and "height" will be undefined until the ResizeObserver takes itsfirst measurement.
It's possible to apply styles conditionally based on the width / height of anelement using a CSS-in-JS solution, which is the basic idea behindcontainer/element queries:
By default the library provides transpiled ES5 modules in CJS / ESM module formats.
Polyfilling is recommended to be done in the host app, and not within importedlibraries, as that way consumers have control over the exact polyfills being used.
That said, there's apolyfilledCJS module that can be used for convenience (Not affecting globals):
importuseResizeObserverfrom"use-resize-observer/polyfilled";
MIT
About
A React hook that allows you to use a ResizeObserver to measure an element's size.
Topics
Resources
License
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
