'Use a slider to scroll a horizontal scrollView in ReactNative

I am trying to set up a slider inside a horizontal ScrollView that would allow me to scroll the page faster. I am able to link position of the page to the value of the slider, so that when I scroll the page, the thumb of the slider moves accordingly.

I am using React Native Slider and a ScrollView. Here is the result that I am unfortunately having.

What I get

I am quite new to RN, so I am probably missing something important here.

class Comp extends Component {

  state = {
    width : 0, 
    value : 0, 
    cursor : 0
  }

  moveTheCursor = (val) => {
    this.scrollView.scrollTo({x: val, y: 0, animated: true})
  }

  scrollTheView = (event) => {
    this.setState({
      value : Math.floor(event.nativeEvent.contentOffset.x),
      cursor : Math.floor(event.nativeEvent.contentOffset.x)
    })
  }

  checkWidth = ({nativeEvent}) => {
    arrayWidth.push(nativeEvent.layout.width)
    let ww = (arrayWidth[0] * this.props.data.length) - Math.round(Dimensions.get('window').width);
    this.setState({
      width : ww,
    })
  }

  render() {
    return (
      <React.Fragment>
        <ScrollView 
          ref={ref => this.scrollView = ref}
          horizontal
          style={styles.car}
          scrollEventThrottle={1}
          onScroll={this.scrollTheView}
          showsHorizontalScrollIndicator={false}
          decelerationRate={0}
          //snapToInterval={200} //your element width
          snapToAlignment={"center"}
        >

        </ScrollView>
          
        <Slider
          style={styles.containerSlide}
          thumbImage={require("./../../assets/img/buttons/thumb.png")}
          trackImage={require("./../../assets/img/buttons/bar.png")}
          minimumValue={0}
          maximumValue={this.state.width}
          onValueChange={this.moveTheCursor}
          value={this.state.cursor}
        />
        

      </React.Fragment>
    );
  }
} 

The problem is, when I use the thumb of the slider to scroll the page, it triggers the scroll that inevitably resets the position of the slider thumb, so it is not behaving correctly (flickers but it is mostly inaccurate). Is there a way to fix this loop?



Solution 1:[1]

You can achieve desired behaviour using Slider's onSlidingStart and onSlidingComplete + ScrollView's scrollEnabled

It can look like

....
const [isSliding, setIsSliding] = useState(false);
....
<ScrollView scrollEnabled={!isSliding}>
   <Slider 
      onSlidingStart={() => setIsSliding(true)}
      onSlidingComplete={() => setIsSliding(false)}
   />
</ScrollView>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CyxouD