react-nativegesturereact-animations

Changing Styles of Elements by Pan Gesture in React Native


I have a divided screen by squares and need to change their colors by touching with a finger continuously with pan gesture.

enter image description here

At first, I thought I could do that by getting position of my finger by pan handler and find which element is located in that location, so that I could change it's color. But it didn't work as I thought. I am stucked at this problem and wondering about your opinions.


Solution

  • Provide a PanResponder for the parent View of those squares.

    // define the constants
    const rows = 10;
    const columns = 5;
    const {width, height} = Dimensions.get('window');
    

    Inside onPanResponderMove write this logic.

     onPanResponderMove: (evt, gestureState) => {
        let i = 0;
        let x = evt.nativeEvent.pageX;
        let y = evt.nativeEvent.pageY;
        let percentageX = Math.floor(x / (width / columns));
        let percentageY = Math.floor(y / (height / rows));
        i = percentageX + columns * percentageY;
        this.onChangeItem(i);  // <-- i will provide you the index of current touch 
      },
    

    Inside onChangeItem function check when the index is changing while moving finger.

    onChangeItem = (index) => {
      if (this.index !== index) {
        // do operations here with index.
      }
    };
    
    ....
    

    Here is my Example code: PanhandlerAnimations

    Result:

    enter image description here