Skip to content

Commit 2c91884

Browse files
committed
Adds ability to snap to index.
1 parent 93e9235 commit 2c91884

1 file changed

Lines changed: 18 additions & 0 deletions

File tree

src/WheelPicker.tsx

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,10 @@ const WheelPicker: React.FC<Props> = ({
4949
}) => {
5050
const flatListRef = useRef<FlatList>(null);
5151
const [scrollY] = useState(new Animated.Value(0));
52+
const flatList = useRef(null)
53+
54+
const SCROLL_DID_STOP_TIMEOUT = 500
55+
const lastScrollTimestamp = useRef(new Date().getTime())
5256

5357
const containerHeight = (1 + visibleRest * 2) * itemHeight;
5458
const [scrollIndex, setScrollIndex] = useState(selectedIndex)
@@ -96,6 +100,19 @@ const WheelPicker: React.FC<Props> = ({
96100
}, [selectedIndex]);
97101

98102

103+
useEffect(() => {
104+
const intervalID = setInterval(() => {
105+
const time = new Date().getTime()
106+
const difference = time - lastScrollTimestamp.current
107+
if (difference > SCROLL_DID_STOP_TIMEOUT) {
108+
flatList.current?.scrollToIndex({ index: scrollIndex, animated: true })
109+
}
110+
}, 100)
111+
return () => {
112+
clearInterval(intervalID)
113+
}
114+
}, [])
115+
99116
useEffect(() => {
100117
if (onChange) {
101118
onChange(scrollIndex)
@@ -113,6 +130,7 @@ const WheelPicker: React.FC<Props> = ({
113130
const positionY = event?.nativeEvent?.contentOffset?.y ?? 0;
114131
const index = Math.round(positionY / itemHeight)
115132
setScrollIndex(index)
133+
lastScrollTimestamp.current = new Date().getTime()
116134
}
117135

118136
return (

0 commit comments

Comments
 (0)