I use PanResponder on a FlatList of components. Each one is injected with the panHandlers
from a single created PanResponder (PanResponder.create
). Because the list can potentially grow into the hundreds, I didn't want hundreds of responders. All the components share the same panHandlers.
const panResponder = PanResponder.create();
const panHandlers = useRef(panResponder?.panHandlers);
<FlatList
renderItem={
<View>
<DragHandle
index={index}
panHandlers={panHandlers.current}
/>
</View>
}
/>
Note that the item index
is available at the DragHandle
level. However I don't have access to index
in the handler itself and so then need to resort to complex calculations which seem really redundant. Furthermore, the accuracy of those calculations depends on assumptions, like constant list item height for example. (The yToIndex
function included in the handler below uses rowHeightRef.current
).
onPanResponderGrant: (evt, gestureState) => {
...
currIdxRef.current = yToIndex(gestureState.y0);
},
const yToIndex =
...
const index = Math.min(
(filteredSongIds?.length ?? 0) - 1,
Math.max(
0,
Math.floor(
(scrollOffsetYRef.current + y - flatListParentYRef.current) /
rowHeightRef.current
...
);
Normally this is not a problem but recently I wanted to add line breaks to the UI of the list. This caused the index
of every item after the first break to be incorrectly calculated due the extra height space of the breaks.
How can I inject index
into the handler?
Or do I really need to create multiple Responders? If so, the previous question still stands.