Search code examples
react-nativescrollview

How to go bottom of the ScrollView as soon as screen is loaded?


I have ScrollView like follows,

render() {
 switch(mode) {
        case 'backNavigation': 
            return(
                <View style={[containerView, backNavigationHeaderView]} >
                    <TouchableOpacity onPress={() => leftAction()}  style={{marginRight: 24}}>
                        <Icons name='backArrow'/>
                    </TouchableOpacity>
                    <View style={{width: '81%'}}>
                        <ScrollView
                            contentContainerStyle={{alignItems: 'center'}}
                            horizontal
                            showsHorizontalScrollIndicator={false}
                            alwaysBounceHorizontal={false}
                            ref={this.setScrollViewRef}
                            onContentSizeChange={() => {
                                if(this.scrollView)
                                this.scrollView.scrollToEnd({ animated: true, index: -1 }, 200);
                              }}
                        >
                            <Text numberOfLines={1} style={[singleTitleStyle]}>{this.renderHeaderTitle(title)}</Text>
                        </ScrollView>
                    </View>
                </View>
            );

}

As soon as screen is loaded getting following error,

Cannot read the property ScrollToEnd of undefined

I tried this SO Solution. But it didn't help me.

Can some one help me on this? Thank You.

Edit 1 This is how I set the reference

setScrollViewRef(element) {
    this.scrollView = element;
}

Solution

  • use React.createRef()

    constructor(props) {
      super(props)
      this.scrollView = React.createRef();
    }
    render() {
      <ScrollView
        contentContainerStyle={{alignItems: 'center'}}
        horizontal
        showsHorizontalScrollIndicator={false}
        alwaysBounceHorizontal={false}
        ref={this.scrollView}
        onContentSizeChange={() => {
          if(this.scrollView)
          this.scrollView.current.scrollToEnd({ animated: true, index: -1 }, 200);
        }}>
      </ScrollView>
    }