Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scrollTo is undefined on animated ScrollView

Tags:

react-native

When using Animated.createAnimatedComponent(ScrollView) to create an animated ScrollView it's not longer possible to use scrollTo.

const AnimatedScrollView = Animated.createAnimatedComponent(ScrollView);

<AnimatedScrollView ref={(ref) => this.list = ref}>
  <View style={{height: 1000}} />
</AnimatedScrollView>

Calling this.list.scrollTo({x: 0, y: 0}) gives the following error:

_this.list.scrollTo is not a function

It works fine on a normal ScrollView. Is there any way to solve this?

like image 367
David Avatar asked Feb 05 '17 11:02

David


2 Answers

@max23_ 's answer might work for now, but is not the correct way of doing it - as a rule of thumb, we should never access private variables directly as these are often subject to change. (edit: no disrespect :-) )

Due to this pull request, the new and future-proof way of getting the wrapped component's ref is to use the getNode() utility method, as accessing private variables (prepended with _) is not safe from future API changes.

So, the new way of doing it is

ref={c => (this.myRef = c)}

and then when calling the method, doing

this.myRef.getNode().scrollTo({
  y: 0,
  animated: true,
});

:-)

like image 117
jhm Avatar answered Nov 17 '22 11:11

jhm


Try this to get the ref of the component returns from Animated.createAnimatedComponent method:

ref={(ref) => this.list = ref._component}

Then, calling this.list.scrollTo({x: 0, y: 0}) should work.

like image 23
max23_ Avatar answered Nov 17 '22 11:11

max23_