Wee
Wee

Reputation: 31

React native null is not an object (evaluating '_scrollView.scrollTo') on Android

React native null is not an object (evaluating '_scrollView.scrollTo') on Android

  componentDidMount() {

      let scrollValue = 0;
      setInterval(function(){
          scrollValue = scrollValue + width;   // width = screen width
          _scrollView.scrollTo({x: scrollValue})
      }, 3000);
}


<ScrollView
ref={(scrollView) => { _scrollView = scrollView; }}
horizontal={true} pagingEnabled={true} >
 {items}
</ScrollView>

it's work auto slide content but when I'm going back from another page it's return error null is not an object (evaluating '_scrollView.scrollTo') I don't know about that

Upvotes: 3

Views: 7252

Answers (2)

Sk Sunny
Sk Sunny

Reputation: 71

you have to check if _scrollView not null

if(this._scrollView != null){
 scrollValue = scrollValue + width;
 this._scrollView.scrollTo({x: scrollValue})
}

render() {
  // ...
  return (
    <ScrollView
      ref={scrollView => this._scrollView = scrollView}
      horizontal={true}
      pagingEnabled={true}
    >
      {items}
    </ScrollView>
  )
}

I hope it will work as I resolved my issue like that way..

Upvotes: 2

Jannik S.
Jannik S.

Reputation: 901

You should save the reference on this. Even so it might work if the reference is in some other scope you will run into problems when multiple ScrollViews are mounted.

componentDidMount() {
  let scrollValue = 0;
  setInterval(() => {
      scrollValue = scrollValue + width;
      this._scrollView.scrollTo({x: scrollValue})
  }, 3000);
}

render() {
  // ...
  return (
    <ScrollView
      ref={scrollView => this._scrollView = scrollView}
      horizontal={true}
      pagingEnabled={true}
    >
      {items}
    </ScrollView>
  )
}

Be aware that this has to be binded by your-self when you create custom methods in your component

scrollListToLeft = () => {
  this._scrollView.scrollTo({x: 0})
}

Upvotes: 0

Related Questions