-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathindex.native.js
58 lines (53 loc) · 1.27 KB
/
index.native.js
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
/**
* External dependencies
*/
import { View, StyleSheet } from 'react-native';
/**
* WordPress dependencies
*/
import { useState, useCallback } from '@wordpress/element';
/**
* Hook which allows to listen the resize event of any target element when it changes sizes.
*
* @return {[JSX.Element, { width: number, height: number } | null]} An array of {Element} `resizeListener` and {?Object} `sizes` with properties `width` and `height`
*
* @example
*
* ```js
* const App = () => {
* const [ resizeListener, sizes ] = useResizeObserver();
*
* return (
* <View>
* { resizeListener }
* Your content here
* </View>
* );
* };
* ```
*
*/
const useResizeObserver = () => {
const [ measurements, setMeasurements ] = useState( null );
const onLayout = useCallback( ( { nativeEvent } ) => {
const { width, height } = nativeEvent.layout;
setMeasurements( ( prevState ) => {
if (
! prevState ||
prevState.width !== width ||
prevState.height !== height
) {
return {
width: Math.floor( width ),
height: Math.floor( height ),
};
}
return prevState;
} );
}, [] );
const observer = (
<View style={ StyleSheet.absoluteFill } onLayout={ onLayout } />
);
return [ observer, measurements ];
};
export default useResizeObserver;