-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathREADME.md
311 lines (217 loc) · 10.1 KB
/
README.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# Handle element resizes like it's 2022!
<img src="https://img.shields.io/npm/dm/react-resize-detector?style=flat-square"> <img src="https://badgen.net/bundlephobia/minzip/react-resize-detector?style=flat-square"> <img src="https://badgen.net/bundlephobia/tree-shaking/react-resize-detector?style=flat-square">
#### [Live demo](http://maslianok.github.io/react-resize-detector/)
Nowadays browsers support element resize handling natively using [ResizeObservers](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver). The library uses these observers to help you handle element resizes in React.
🐥 Tiny <a href="https://bundlephobia.com/result?p=react-resize-detector" target="__blank">~3kb</a>
🐼 Written in TypeScript
🦁 Supports Function and Class Components
🐠 Used by <a href="https://github.com/maslianok/react-resize-detector/network/dependents" target="__blank">20k+ repositories</a>
🦄 Generating 35M+ downloads/year
No `window.resize` listeners! No timeouts! No 👑 viruses! :)
<i>TypeScript-lovers notice: starting from v6.0.0 you may safely remove `@types/react-resize-detector` from you deps list.</i>
## Installation
```ssh
npm i react-resize-detector
// OR
yarn add react-resize-detector
```
and
```jsx
import ResizeObserver from 'react-resize-detector';
```
## Examples
Starting from v6.0.0 there are 3 recommended ways to work with `resize-detector` library:
#### 1. React hook (new in v6.0.0)
```jsx
import { useResizeDetector } from 'react-resize-detector';
const CustomComponent = () => {
const { width, height, ref } = useResizeDetector();
return <div ref={ref}>{`${width}x${height}`}</div>;
};
```
<details><summary>With props</summary>
```js
import { useResizeDetector } from 'react-resize-detector';
const CustomComponent = () => {
const onResize = useCallback(() => {
// on resize logic
}, []);
const { width, height, ref } = useResizeDetector({
handleHeight: false,
refreshMode: 'debounce',
refreshRate: 1000,
onResize
});
return <div ref={ref}>{`${width}x${height}`}</div>;
};
```
</details>
<details><summary>With custom ref</summary>
```js
import { useResizeDetector } from 'react-resize-detector';
const CustomComponent = () => {
const targetRef = useRef();
const { width, height } = useResizeDetector({ targetRef });
return <div ref={targetRef}>{`${width}x${height}`}</div>;
};
```
</details>
#### 2. HOC pattern
```jsx
import { withResizeDetector } from 'react-resize-detector';
const CustomComponent = ({ width, height }) => <div>{`${width}x${height}`}</div>;
export default withResizeDetector(CustomComponent);
```
#### 3. Child Function Pattern
```jsx
import ReactResizeDetector from 'react-resize-detector';
// ...
<ReactResizeDetector handleWidth handleHeight>
{({ width, height }) => <div>{`${width}x${height}`}</div>}
</ReactResizeDetector>;
```
<details><summary>Full example (Class Component)</summary>
```jsx
import React, { Component } from 'react';
import { withResizeDetector } from 'react-resize-detector';
const containerStyles = {
height: '100vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
};
class AdaptiveComponent extends Component {
state = {
color: 'red'
};
componentDidUpdate(prevProps) {
const { width } = this.props;
if (width !== prevProps.width) {
this.setState({
color: width > 500 ? 'coral' : 'aqua'
});
}
}
render() {
const { width, height } = this.props;
const { color } = this.state;
return <div style={{ backgroundColor: color, ...containerStyles }}>{`${width}x${height}`}</div>;
}
}
const AdaptiveWithDetector = withResizeDetector(AdaptiveComponent);
const App = () => {
return (
<div>
<p>The rectangle changes color based on its width</p>
<AdaptiveWithDetector />
</div>
);
};
export default App;
```
</details>
<details><summary>Full example (Functional Component)</summary>
```jsx
import React, { useState, useEffect } from 'react';
import { withResizeDetector } from 'react-resize-detector';
const containerStyles = {
height: '100vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
};
const AdaptiveComponent = ({ width, height }) => {
const [color, setColor] = useState('red');
useEffect(() => {
setColor(width > 500 ? 'coral' : 'aqua');
}, [width]);
return <div style={{ backgroundColor: color, ...containerStyles }}>{`${width}x${height}`}</div>;
};
const AdaptiveWithDetector = withResizeDetector(AdaptiveComponent);
const App = () => {
return (
<div>
<p>The rectangle changes color based on its width</p>
<AdaptiveWithDetector />
</div>
);
};
export default App;
```
</details>
<br/>
We still support [other ways](https://github.com/maslianok/react-resize-detector/tree/v4.2.1#examples) 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.
## Performance optimization
This library uses the native [ResizeObserver](https://developer.mozilla.org/en-US/docs/Web/API/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.
```jsx
// WRONG - anonymous function
const { ref, width, height } = useResizeDetector({
onResize: () => {
// on resize logic
}
});
// CORRECT - `useCallback` approach
const onResize = useCallback(() => {
// on resize logic
}, []);
const { ref, width, height } = useResizeDetector({ onResize });
```
## Refs
_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`](https://reactjs.org/docs/reactdom.html#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`
<details><summary>HOC pattern example</summary>
```jsx
import { withResizeDetector } from 'react-resize-detector';
const CustomComponent = ({ width, height, targetRef }) => <div ref={targetRef}>{`${width}x${height}`}</div>;
export default withResizeDetector(CustomComponent);
```
</details>
<details><summary>Child Function Pattern example</summary>
```jsx
import ReactResizeDetector from 'react-resize-detector';
// ...
<ReactResizeDetector handleWidth handleHeight>
{({ width, height, targetRef }) => <div ref={targetRef}>{`${width}x${height}`}</div>}
</ReactResizeDetector>;
```
</details>
## API
| 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](https://lodash.com/docs#debounce) 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](https://lodash.com/docs/4.17.11#throttle) for more info | `undefined` |
| observerOptions | Object | These options will be used as a second parameter of [`resizeObserver.observe`](https://developer.mozilla.org/en-US/docs/Web/API/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](https://github.com/Primajin) for posting this [snippet](https://github.com/maslianok/react-resize-detector/issues/145)
```jsx
const { ResizeObserver } = window;
beforeEach(() => {
delete window.ResizeObserver;
window.ResizeObserver = jest.fn().mockImplementation(() => ({
observe: jest.fn(),
unobserve: jest.fn(),
disconnect: jest.fn()
}));
wrapper = mount(<MyComponent />);
});
afterEach(() => {
window.ResizeObserver = ResizeObserver;
jest.restoreAllMocks();
});
it('should do my test', () => {
// [...]
});
```
## License
MIT
## ❤️
Show us some love and STAR ⭐ the project if you find it useful