Search code examples
javascriptreactjsreact-nativereact-native-navigation

How to create multiple panresponders in react native?


I know how to create a panResponder but im not sure how to create multiple instances of it. for eg. I have an array of elements that moves independently and i have to attach each reponders respectively to the element to get the layout values from it. Any help would be appreciated been stuck for long time.

    pan = new Animated.ValueXY();

    panResponder = PanResponder.create({
        onMoveShouldSetPanResponder: () => true,
        onPanResponderGrant: (evt, gestureState) => {
            this.pan.setOffset(this.pan.__getValue());
            this.pan.setValue({ x: 0, y: 0 });
        },

    onPanResponderMove: Animated.event([
      null,
      { dx: this.pan.x, dy: this.pan.y }
    ]),
    onPanResponderRelease: (e) => {
      console.log(this.pan.getLayout(), 'layout values')
      this.pan.flattenOffset();
    }
  });

 render() {
      
    return (
      <View style={styles.container}>
        <View  style={{backgroundColor:'red', height:300, width:300}}>
            <Animated.View
                pointerEvents="box-none"
                style={[styles.box, {
                    transform: [{ translateX: this.pan.x }, { translateY: this.pan.y }]
                }]}
                {...this.panResponder.panHandlers}>
        </Animated.View>
      </View>
      </View>
    );
  }

Solution

    1. You could create a multiple instances of refs to the Parent component itself according to the array and attach PanResponder to it
    
    class Parent extends Component {
      constructor(props) {
        super(props);
        this.panRefs = this.props.elements.map(e => React.createRef());
    
        this.panRefs.forEach(panRef => {
          panRef.current = PanResponder.create({})
        });
      }
    
      render() {}
    }
    
    1. You could create a child component and attach to a PanResponder to it ref.
    class Parent extends Component {
      render() {
        const arr = Array.from({ length: 8 });
    
        return (
          <View>
            {arr.map((elem, idx) => {
              return <Child elem={elem} key={idx} />
            })}
          </View>
        )
      }
    }
    
    class Child extends Component {
      constructor(props) {
        super(props);
    
        this.panRef = React.createRef();
    
        this.panRef.current = PanResponder.create({})
      }
    
      render() {}
    }