react-nativeswipereact-native-gesture-handler

How to swipe back an item when another item is pressed or swiped using react-native-gesture-handler?


I am trying to cancel the swipe action (swipe back) of a swiped item, when another item is swiped or pressed, using react-native-gesture-handler. I tried to get help from this snack post, but I couldn't achieve. Also did the methods mentioned in this post, but again no luck, I am stuck.

I am writing briefly what I did: List.js file:

const List = () => {
  let prevOpenedRow;
  let row = []
  ...
  return (
   <FlatList 
     data={dataArray}
     keyExtractor={(item)=>item.id}
     renderItem={({item, index})=> <Child item={item} index={index} row={row} prevOpenedRow={prevOpenedRow}  />}
   />
)}

Child.js file:

const Child = ({item, index, row, prevOpenedRow}) => {

   const closeRow = (index) => {
      console.log("prevOpenedRow",prevOpenedRow)  // everytime output is undefined
      if (prevOpenedRow && prevOpenedRow !== row[index]) {
        prevOpenedRow.close()
      }
      prevOpenedRow = row[index]
   }
return (
  <Swipeable
      renderRightActions={swipeRightComps}
      ref={(ref) => (row[index] = ref)}
      onSwipeableOpen={(direction) => {
        closeRow(index)
      }}
  >
   ......
  </Swipeable>
)}

Solution

  • You need to manage the preOpenedRow in a place where changes persist. You need to track the opened row using either refs or React's state

    Try something like below :

    List.js

    const prevOpenedRow = useRef(null);
    

    Child.js

    const closeRow = (index) => {
    if (prevOpenedRow.current && prevOpenedRow.current !== row[index]) {
      prevOpenedRow.current.close();
    }
    prevOpenedRow.current = row[index];
    };