A Cross-Browser, Event-based, Element Resize Detection for React
Installations
npm install react-resize-detector
Developer
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
Yes
Node Version
20.14.0
NPM Version
10.7.0
Statistics
1,259 Stars
510 Commits
91 Forks
9 Watching
3 Branches
38 Contributors
Updated on 27 Nov 2024
Bundle Size
5.04 kB
Minified
2.03 kB
Minified + Gzipped
Languages
TypeScript (90.96%)
CSS (5.99%)
JavaScript (2.12%)
HTML (0.93%)
Total Downloads
Cumulative downloads
Total Downloads
363,986,692
Last day
-1.5%
277,321
Compared to previous day
Last week
6.9%
1,414,128
Compared to previous week
Last month
8.7%
5,772,880
Compared to previous month
Last year
-21.2%
80,609,083
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
1
Handle element resizes like it's 2024!
Live demo
Modern browsers now have native support for detecting element size changes through ResizeObservers. This library utilizes ResizeObservers to facilitate managing element size changes in React applications.
🐥 Tiny ~2kb
🐼 Written in TypeScript
🐠 Used by 170k repositories
🦄 Produces 100 million downloads annually
No window.resize
listeners! No timeouts!
Is it necessary for you to use this library?
Container queries now work in all major browsers. It's very likely you can solve your task using pure CSS.
Example
1<div class="post"> 2 <div class="card"> 3 <h2>Card title</h2> 4 <p>Card content</p> 5 </div> 6</div>
1.post { 2 container-type: inline-size; 3} 4 5/* Default heading styles for the card title */ 6.card h2 { 7 font-size: 1em; 8} 9 10/* If the container is larger than 700px */ 11@container (min-width: 700px) { 12 .card h2 { 13 font-size: 2em; 14 } 15}
Installation
1npm i react-resize-detector 2// OR 3yarn add react-resize-detector
Example
1import { useResizeDetector } from 'react-resize-detector'; 2 3const CustomComponent = () => { 4 const { width, height, ref } = useResizeDetector(); 5 return <div ref={ref}>{`${width}x${height}`}</div>; 6};
With props
1import { useResizeDetector } from 'react-resize-detector'; 2 3const CustomComponent = () => { 4 const onResize = useCallback(() => { 5 // on resize logic 6 }, []); 7 8 const { width, height, ref } = useResizeDetector({ 9 handleHeight: false, 10 refreshMode: 'debounce', 11 refreshRate: 1000, 12 onResize 13 }); 14 15 return <div ref={ref}>{`${width}x${height}`}</div>; 16};
With custom ref
It's not advised to use this approach, as dynamically mounting and unmounting the observed element could lead to unexpected behavior.
1import { useResizeDetector } from 'react-resize-detector'; 2 3const CustomComponent = () => { 4 const targetRef = useRef(); 5 const { width, height } = useResizeDetector({ targetRef }); 6 return <div ref={targetRef}>{`${width}x${height}`}</div>; 7};
API
Prop | Type | Description | Default |
---|---|---|---|
onResize | Func | Function that will be invoked with width , height and ResizeObserver entry arguments | undefined |
handleWidth | Bool | Trigger onResize on width change | true |
handleHeight | Bool | Trigger onResize on height change | true |
skipOnMount | Bool | Do not trigger onResize when a component mounts | false |
refreshMode | String | Possible values: throttle and debounce See lodash docs for more information. undefined - callback will be fired for every frame | undefined |
refreshRate | Number | Use this in conjunction with refreshMode . Important! It's a numeric prop so set it accordingly, e.g. refreshRate={500} | 1000 |
refreshOptions | Object | Use this in conjunction with refreshMode . An object in shape of { leading: bool, trailing: bool } . Please refer to lodash's docs for more info | undefined |
observerOptions | Object | These options will be used as a second parameter of resizeObserver.observe method. | undefined |
targetRef | Ref | Use this prop to pass a reference to the element you want to attach resize handlers to. It must be an instance of React.useRef or React.createRef functions | undefined |
Testing with Enzyme and Jest
Thanks to @Primajin for posting this snippet
1const { ResizeObserver } = window; 2 3beforeEach(() => { 4 delete window.ResizeObserver; 5 window.ResizeObserver = jest.fn().mockImplementation(() => ({ 6 observe: jest.fn(), 7 unobserve: jest.fn(), 8 disconnect: jest.fn() 9 })); 10 11 wrapper = mount(<MyComponent />); 12}); 13 14afterEach(() => { 15 window.ResizeObserver = ResizeObserver; 16 jest.restoreAllMocks(); 17}); 18 19it('should do my test', () => { 20 // [...] 21});
License
MIT
❤️
Show us some love and STAR ⭐ the project if you find it useful
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
4 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-gcx4-mw62-g8wm
Reason
Found 1/5 approved changesets -- score normalized to 2
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 27 are checked with a SAST tool
Score
3.2
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More