Search code examples
react-nativeexposcrollview

react native expo horizontal ScrollView ref.scrollTo it teleports me without animation


horizontal ScrollView ref.scrollTo it teleports me without animation i've been trying to find a way to fix it but didn't find anything about it

  useEffect(()=>{
    if(styleActive=="Label2"){
      ImageScroller.current?.scrollTo({x: 500, animated: true });
    }
  },[styleActive])
<ScrollView 
          ref={ImageScroller}
          horizontal
          scrollEnabled={true}
          style={{ height: 264,marginTop: 30 }}
        >
          <Image
            source={item.image}
            style={{ height: 264, width: 368, marginLeft: windowWidth - 270 }}
            resizeMode="contain"
          />
          <Image
            source={require("../assets/Images/ColdCup.png")}
            style={{ height: 264, width: 368, marginLeft: windowWidth - 270 }}
            resizeMode="contain"
          />
          <Image
            source={require("../assets/Images/HotCup.png")}
            style={{ height: 264, width: 368, marginLeft: windowWidth - 270 }}
            resizeMode="contain"
          />
</ScrollView>

Solution

  • You can achieve your desired behavior by adding couple of changes to your code ,Change the condition of the if statement inside the useEffect like this,

      if (styleActive === 'Label2' && ImageScroller.current) {
          // Wait for the ScrollView to be fully rendered before scrolling
          ImageScroller.current.scrollTo({ x: 500, animated: true });
        }

    And add onLayout attribute to the ScrollView

     onLayout={() => {
            // This ensures that the ScrollView has been fully rendered and initialized before calling scrollTo
            if (styleActive === 'Label2' && ImageScroller.current) {
              ImageScroller.current.scrollTo({ x: 500, animated: true });
            }
          }}

    Try after adding these.