React-Native ScrollView lost position on setState

Viewed 1143

I need to change state of a row within ScrollView (the same in ListView) but using setState of component makes scroll reset its position to top.

          <ScrollView
        {...this.panResponder.panHandlers}
        bounces={false}
        onScroll={() => {
          this.scrollIsScrolling = true;
        }}
        onTouchEnd={() => {
          this.scrollIsScrolling = false;
        }}
        onMomentumScrollEnd={() => {
          this.scrollIsScrolling = false;
        }}
        scrollEnabled={this.state.scrollEnabled}
        removeClippedSubviews={false}
        enableEmptySections
        style={styles.listView}
      >
        {this.props.settings.map((setting, i) => {
          return (
            <IntegrationSlideupCell
              key={i}
              title={setting.title}
              selected={this.state.selectedSetting === i}
              selectedGradient={this.props.integration.selectedGradient}
              onPress={() => {
                this.setState({ selectedSetting: i });
              }}
            />
          );
        })}
      </ScrollView>

UPD: Removing custom panHandlers, onScroll, onTouchEnd, onMomentumScrollEnd handlers and other props makes no difference. The only thing that causes it setState.

1 Answers

Using the offset approach, If "IntegrationSlideupCell" is given a fixed height, then you can offset by that width and store the offset to state

this.state = {
    contentOffset: {y: 0},
}

function handlePress() {
   offset = HEIGHT_OF_CONTAINER;
   newOffset = this.state.contentOffset.y + offset;    
   this.setState({contentOffset: {y: newOffset}, selectedSetting: i });
} 

          <ScrollView
    {...this.panResponder.panHandlers}
    bounces={false}
    contentOffset={this.state.contentOffset}
    onScroll={() => {
      this.scrollIsScrolling = true;
    }}
    onTouchEnd={() => {
      this.scrollIsScrolling = false;
    }}
    onMomentumScrollEnd={() => {
      this.scrollIsScrolling = false;
    }}
    scrollEnabled={this.state.scrollEnabled}
    removeClippedSubviews={false}
    enableEmptySections
    style={styles.listView}
  >
    {this.props.settings.map((setting, i) => {
      return (
        <IntegrationSlideupCell
          key={i}
          title={setting.title}
          selected={this.state.selectedSetting === i}
          selectedGradient={this.props.integration.selectedGradient}
          onPress={handlePress.bind(this)}
        />
      );
    })}
  </ScrollView>
   
   
Related