Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/rehooks/component-size
React hook for determining the size of a component
https://github.com/rehooks/component-size
component element hook react size
Last synced: 13 days ago
JSON representation
React hook for determining the size of a component
- Host: GitHub
- URL: https://github.com/rehooks/component-size
- Owner: rehooks
- License: mit
- Created: 2018-10-25T19:39:39.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2023-02-05T10:55:06.000Z (almost 2 years ago)
- Last Synced: 2024-04-28T09:43:16.039Z (6 months ago)
- Topics: component, element, hook, react, size
- Language: JavaScript
- Homepage:
- Size: 137 KB
- Stars: 238
- Watchers: 4
- Forks: 23
- Open Issues: 18
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- fucking-awesome-react-hooks - `@rehooks/component-size`
- awesome-react-hooks-cn - `@rehooks/component-size`
- awesome-react-hooks - `@rehooks/component-size`
- awesome-react-hooks - `@rehooks/component-size`
README
# `@rehooks/component-size`
## Install
```sh
yarn add @rehooks/component-size
```## Usage
```js
import { useRef } from 'react'
import useComponentSize from '@rehooks/component-size'function MyComponent() {
let ref = useRef(null)
let size = useComponentSize(ref)
// size == { width: 100, height: 200 }
let { width, height } = size
let imgUrl = `https://via.placeholder.com/${width}x${height}`return (
)
}
```## ResizeObserver
[Resize Observer](https://developers.google.com/web/updates/2016/10/resizeobserver)
is 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.> [Can i use ResizeObserver?](https://caniuse.com/#feat=resizeobserver)
### Polyfill
You can import the
[polyfill](https://github.com/que-etc/resize-observer-polyfill) directly from here```sh
yarn add resize-observer-polyfill
```Then import it in your app:
```js
import 'resize-observer-polyfill'
```If you are using Webpack (or similar) you could use [dynamic
imports](https://webpack.js.org/api/module-methods/#import-), to load the
Polyfill only if needed. A basic implementation could look something like this:```js
loadPolyfills()
.then(() => /* Render React application now that your Polyfills are ready */)/**
* Do feature detection, to figure out which polyfills needs to be imported.
**/
function loadPolyfills() {
const polyfills = []if (!supportsResizeObserver()) {
polyfills.push(import('resize-observer-polyfill'))
}return Promise.all(polyfills)
}function supportsResizeObserver() {
return (
'ResizeObserver' in global &&
'ResizeObserverEntry' in global &&
'contentRect' in ResizeObserverEntry.prototype
)
}
```