-2

I have a flatlist with many product . E.g. I click lot 20, it will proceed to screen with product detail. In product detail screen have a search function to other product. If search for lot 1 it will show product detail for lot 1. But when click back button it show the flatlist screen at the position of product 20, I want it to show the flatlist screen at the position of product 1. I am using react native class component. Can someone help?

flatlist.js

 class FlatlistScreen extends React.Component {
  constructor(props) {

    super(props);
    this.state = {
    };

  }

componentDidMount(){

}

render(){
   return(
     <SafeAreaView style={{flex: 1}}>
        <AnimatedFlatList
        style={{flex: 1}}
        ref={(ref) => this.flatListRef = ref}
          data={this.props.APIE}
          renderItem={this.renderItem}
          contentContainerStyle={{paddingTop: Platform.OS !== 'ios' ? HEADER_MAX_HEIGHT : 0,}}
          keyExtractor={item => item._id}
          refreshing={this.state.refreshing}
          removeClippedSubviews={Platform.OS == "android" ? this.state.sticky.length > 0 : true}
          scrollEventThrottle={1}
          refreshControl={
            <RefreshControl
              refreshing={this.state.refreshing}
              onRefresh={
                this.onRefresh.bind(this)
              }
              progressViewOffset={HEADER_MAX_HEIGHT}
            />
          }
          contentInset={{
            top: HEADER_MAX_HEIGHT,
          }}
          contentOffset={{
            y: -HEADER_MAX_HEIGHT,
          }}
          onScroll={Animated.event(
            [{ nativeEvent: { contentOffset: { y: this.state.scrollY } } }],
            { useNativeDriver: true },
          )}
        />
      </SafeAreaView>
)
}
}

productDetail.js

class ProductDetailScreen extends React.Component {
  constructor(props) {

    super(props);
    this.state = {
    };

  }

componentDidMount(){
     BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}

handleBackButtonClick() {

    return true;
}

render(){
   return(
       <Text>Product Detail</Text>
   )
}
}
Roann
  • 7
  • 5

1 Answers1

0

On this.renderItem you probably use ProductDetailScreen to render this.props.APIE elements. Well, you could add a prop to ProductDetailScreen like:

<ProductDetailScreen onGoBack={this.scrollToTop} /*other props*/ />

this.scrollToTop looks like:

scrollToTop() {
   this.flatListRef.scrollToOffset({ animated: true, offset: 0 });
}

So this is the function that scoll the Flatlist to top.

Ok, now on ProductDetailScreen component, when we go back (I mean, on handleBackButtonClick function) we can call props.onGoBack():

class ProductDetailScreen extends React.Component {
    ...
    handleBackButtonClick() {
       props.onGoBack();
       return true;
    }
    ...
}

Thats it. Now when you go back from product details, FlatList will scroll to top.

Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30