- Notifications
You must be signed in to change notification settings - Fork23
React hook for determining the size of a component
License
NotificationsYou must be signed in to change notification settings
rehooks/component-size
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
yarn add @rehooks/component-size
import{useRef}from'react'importuseComponentSizefrom'@rehooks/component-size'functionMyComponent(){letref=useRef(null)letsize=useComponentSize(ref)// size == { width: 100, height: 200 }let{ width, height}=sizeletimgUrl=`https://via.placeholder.com/${width}x${height}`return(<divstyle={{width:'100%',height:'100%'}}><imgref={ref}src={imgUrl}/></div>)}
Resize Observeris the API is used to determine if an element is resized. Browser support is pretty good in Chrome, but is still missing support in other major browsers.
You can import thepolyfill directly from here
yarn add resize-observer-polyfill
Then import it in your app:
import'resize-observer-polyfill'
If you are using Webpack (or similar) you could usedynamicimports, to load thePolyfill only if needed. A basic implementation could look something like this:
loadPolyfills().then(()=>/* Render React application now that your Polyfills are ready */)/*** Do feature detection, to figure out which polyfills needs to be imported.**/functionloadPolyfills(){constpolyfills=[]if(!supportsResizeObserver()){polyfills.push(import('resize-observer-polyfill'))}returnPromise.all(polyfills)}functionsupportsResizeObserver(){return('ResizeObserver'inglobal&&'ResizeObserverEntry'inglobal&&'contentRect'inResizeObserverEntry.prototype)}
About
React hook for determining the size of a component
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
No releases published
Packages0
No packages published
Uh oh!
There was an error while loading.Please reload this page.
Contributors7
Uh oh!
There was an error while loading.Please reload this page.