Gathering detailed insights and metrics for react-resize-detector-enhanced
Gathering detailed insights and metrics for react-resize-detector-enhanced
Gathering detailed insights and metrics for react-resize-detector-enhanced
Gathering detailed insights and metrics for react-resize-detector-enhanced
A Cross-Browser, Event-based, Element Resize Detection for React v18.0
npm install react-resize-detector-enhanced
Typescript
Module System
Node Version
NPM Version
67.5
Supply Chain
92.9
Quality
75.1
Maintenance
100
Vulnerability
99.6
License
TypeScript (94.49%)
JavaScript (5.51%)
Total Downloads
496
Last Day
1
Last Week
5
Last Month
16
Last Year
151
MIT License
1 Stars
371 Commits
11 Branches
1 Contributors
Updated on Nov 25, 2022
Minified
Minified + Gzipped
Latest Version
7.0.2
Package Id
react-resize-detector-enhanced@7.0.2
Unpacked Size
215.13 kB
Size
53.00 kB
File Count
12
NPM Version
8.10.0
Node Version
16.14.1
Cumulative downloads
Total Downloads
Last Day
0%
1
Compared to previous day
Last Week
150%
5
Compared to previous week
Last Month
-5.9%
16
Compared to previous month
Last Year
106.8%
151
Compared to previous year
2
23
An enhanced version of maslianok/react-resize-detector which is configured to work with React v16.8.0 and above.
Nowadays browsers support element resize handling natively using ResizeObservers. The library uses these observers to help you handle element resizes in React.
🐥 Tiny ~3kb
🐼 Written in TypeScript
🦁 Supports Function and Class Components
🐠 Used by 20k+ repositories
🦄 Generating 35M+ downloads/year
No window.resize
listeners! No timeouts! No 👑 viruses! :)
TypeScript-lovers notice: starting from v6.0.0 you may safely remove @types/react-resize-detector
from you deps list.
1npm i react-resize-detector 2// OR 3yarn add react-resize-detector
and
1import ResizeObserver from 'react-resize-detector';
Starting from v6.0.0 there are 3 recommended ways to work with resize-detector
library:
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};
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};
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};
1import { withResizeDetector } from 'react-resize-detector'; 2 3const CustomComponent = ({ width, height }) => <div>{`${width}x${height}`}</div>; 4 5export default withResizeDetector(CustomComponent);
1import ReactResizeDetector from 'react-resize-detector'; 2 3// ... 4 5<ReactResizeDetector handleWidth handleHeight> 6 {({ width, height }) => <div>{`${width}x${height}`}</div>} 7</ReactResizeDetector>;
1import React, { Component } from 'react'; 2import { withResizeDetector } from 'react-resize-detector'; 3 4const containerStyles = { 5 height: '100vh', 6 display: 'flex', 7 alignItems: 'center', 8 justifyContent: 'center' 9}; 10 11class AdaptiveComponent extends Component { 12 state = { 13 color: 'red' 14 }; 15 16 componentDidUpdate(prevProps) { 17 const { width } = this.props; 18 19 if (width !== prevProps.width) { 20 this.setState({ 21 color: width > 500 ? 'coral' : 'aqua' 22 }); 23 } 24 } 25 26 render() { 27 const { width, height } = this.props; 28 const { color } = this.state; 29 return <div style={{ backgroundColor: color, ...containerStyles }}>{`${width}x${height}`}</div>; 30 } 31} 32 33const AdaptiveWithDetector = withResizeDetector(AdaptiveComponent); 34 35const App = () => { 36 return ( 37 <div> 38 <p>The rectangle changes color based on its width</p> 39 <AdaptiveWithDetector /> 40 </div> 41 ); 42}; 43 44export default App;
1import React, { useState, useEffect } from 'react'; 2import { withResizeDetector } from 'react-resize-detector'; 3 4const containerStyles = { 5 height: '100vh', 6 display: 'flex', 7 alignItems: 'center', 8 justifyContent: 'center' 9}; 10 11const AdaptiveComponent = ({ width, height }) => { 12 const [color, setColor] = useState('red'); 13 14 useEffect(() => { 15 setColor(width > 500 ? 'coral' : 'aqua'); 16 }, [width]); 17 18 return <div style={{ backgroundColor: color, ...containerStyles }}>{`${width}x${height}`}</div>; 19}; 20 21const AdaptiveWithDetector = withResizeDetector(AdaptiveComponent); 22 23const App = () => { 24 return ( 25 <div> 26 <p>The rectangle changes color based on its width</p> 27 <AdaptiveWithDetector /> 28 </div> 29 ); 30}; 31 32export default App;
We still support other ways to work with this library, but in the future consider using the ones described above. Please let me know if the examples above don't fit your needs.
This library uses the native ResizeObserver API.
DOM nodes get attached to ResizeObserver.observe
every time the component mounts and every time any property gets changed.
It means you should try to avoid passing anonymous functions to ResizeDetector
, because they will trigger the whole initialization process every time the component rerenders. Use useCallback
whenever it's possible.
1// WRONG - anonymous function 2const { ref, width, height } = useResizeDetector({ 3 onResize: () => { 4 // on resize logic 5 } 6}); 7 8// CORRECT - `useCallback` approach 9const onResize = useCallback(() => { 10 // on resize logic 11}, []); 12 13const { ref, width, height } = useResizeDetector({ onResize });
The below explanation doesn't apply to useResizeDetector
The library is trying to be smart and does not add any extra DOM elements to not break your layouts. That's why we use findDOMNode
method to find and attach listeners to the existing DOM elements. Unfortunately, this method has been deprecated and throws a warning in StrictMode.
For those who want to avoid this warning, we are introducing an additional property - targetRef
. You have to set this prop as a ref
of your target DOM element and the library will use this reference instead of searching the DOM element with help of findDOMNode
1import { withResizeDetector } from 'react-resize-detector'; 2 3const CustomComponent = ({ width, height, targetRef }) => <div ref={targetRef}>{`${width}x${height}`}</div>; 4 5export default withResizeDetector(CustomComponent);
1import ReactResizeDetector from 'react-resize-detector'; 2 3// ... 4 5<ReactResizeDetector handleWidth handleHeight> 6 {({ width, height, targetRef }) => <div ref={targetRef}>{`${width}x${height}`}</div>} 7</ReactResizeDetector>;
Prop | Type | Description | Default |
---|---|---|---|
onResize | Func | Function that will be invoked with width and height 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 |
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});
MIT
Show us some love and STAR ⭐ the project if you find it useful
No vulnerabilities found.
No security vulnerabilities found.