-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathScrollViewWithContext.tsx
68 lines (58 loc) · 2.37 KB
/
ScrollViewWithContext.tsx
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
import type {ForwardedRef} from 'react';
import React, {useMemo, useRef, useState} from 'react';
import type {NativeScrollEvent, NativeSyntheticEvent} from 'react-native';
import {ScrollView} from 'react-native';
const MIN_SMOOTH_SCROLL_EVENT_THROTTLE = 16;
type ScrollContextValue = {
contentOffsetY: number;
scrollViewRef: ForwardedRef<ScrollView>;
};
const ScrollContext = React.createContext<ScrollContextValue>({
contentOffsetY: 0,
scrollViewRef: null,
});
type ScrollViewWithContextProps = {
onScroll: (event: NativeSyntheticEvent<NativeScrollEvent>) => void;
children?: React.ReactNode;
scrollEventThrottle: number;
} & Partial<ScrollView>;
/*
* <ScrollViewWithContext /> is a wrapper around <ScrollView /> that provides a ref to the <ScrollView />.
* <ScrollViewWithContext /> can be used as a direct replacement for <ScrollView />
* if it contains one or more <Picker /> / <RNPickerSelect /> components.
* Using this wrapper will automatically handle scrolling to the picker's <TextInput />
* when the picker modal is opened
*/
function ScrollViewWithContextWithRef({onScroll, scrollEventThrottle, children, ...restProps}: ScrollViewWithContextProps, ref: ForwardedRef<ScrollView>) {
const [contentOffsetY, setContentOffsetY] = useState(0);
const defaultScrollViewRef = useRef<ScrollView>(null);
const scrollViewRef = ref ?? defaultScrollViewRef;
const setContextScrollPosition = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
if (onScroll) {
onScroll(event);
}
setContentOffsetY(event.nativeEvent.contentOffset.y);
};
const contextValue = useMemo(
() => ({
scrollViewRef,
contentOffsetY,
}),
[scrollViewRef, contentOffsetY],
);
return (
<ScrollView
// eslint-disable-next-line react/jsx-props-no-spreading
{...restProps}
ref={scrollViewRef}
onScroll={setContextScrollPosition}
scrollEventThrottle={scrollEventThrottle || MIN_SMOOTH_SCROLL_EVENT_THROTTLE}
>
<ScrollContext.Provider value={contextValue}>{children}</ScrollContext.Provider>
</ScrollView>
);
}
ScrollViewWithContextWithRef.displayName = 'ScrollViewWithContextWithRef';
export default React.forwardRef(ScrollViewWithContextWithRef);
export {ScrollContext};
export type {ScrollContextValue};