Home > Back-end >  How to update a state while scrolling
How to update a state while scrolling

Time:09-06

I have a state and a ref like that :

const [myValue, setMyValue] = useState();

 const scrollViewRef = useRef();

I have a scrollview with multiple views in it :

<ScrollView
    style={styles.optionsContainer}
    horizontal={true}
    ref={scrollViewRef}
 >

<View>
// Some stuff
</>

<View>
// Some stuff
</>

<View>
// Some stuff
</>

</ScrollView>

When the value of myValue state changes, the position of the corresponding view changes thanks to the ref :

 useEffect(() => {

    if (myValue < 24) {
      scrollViewRef.current.scrollTo({ x: 0, y: 0, animated: true })
    }

    if (myValue > 24 && myValue < 50) {
      scrollViewRef.current.scrollTo({ x: 190, y: 0, animated: true });
    }

    if (myValue > 49 && myValue < 75) {
      scrollViewRef.current.scrollTo({ x: 480, y: 0, animated: true });
    }

   
  }, [myValue]);

What I want to do is to keep that feature, but add the reverse possibility : if I scroll by hand, I want to update the value of myValue state.

How can I achieve that ?

CodePudding user response:

Add scroll event listener, initialize it in useEffect, and invoke your updateState functions when scrolls.

useEffect(() => {
       window.addEventListener('scroll', handleScroll);
}, [])

const handleScroll = () => {
   setMyValue(window.scrollTop)
}

CodePudding user response:

What you can do is add onScroll event for scrollView

const onScroll = (event) =>{
    if(event.nativeEvent.contentOffset.x <190){

setMyValue(22)
}

   if(event.nativeEvent.contentOffset.x < 480){

setMyValue(50)
}

  }

return(<ScrollView onScroll={onScroll} >)

Hope it helps, feel free for doubts

  • Related