6

I'm trying to make scroll to the top, if a certain condition is met, in the component's componentWillReceiveProps event ... but nothing happens:

componentWillReceiveProps(nextProps) {
     // some code...

    if (newQuery === query && this.scrollViewRef.current) {
      console.log('Should scroll to top'); // << logs successfully

      this.scrollViewRef.current.scrollTo({
        x: 0,
        y: 0,
        duration: 500,
        animated: true,
      });
    }
  }

Code snippet of how I created ref for the scrollView:

class SearchResult extends React.Component {
  constructor(props) {
    super(props);

    this.scrollViewRef = React.createRef();
  }
//...
}

render method:

render () {
   return (
      <ScrollView
        ref={this.scrollViewRef}
        contentContainerStyle={{ marginVertical: 8 }}
      >
    ...
    )
}

I also tried to scroll manually via a button press ... doesn't work as well

Any help ?

Hend El-Sahli
  • 6,268
  • 2
  • 25
  • 42

3 Answers3

4

For those people who use useRef() method and gets 'xRef.scrollTo' is not a function error, try to use it like xRef.current.scrollTo({[YOUR_PARAMS]}).

I didn't know this current thing and was getting crazy.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Keyyubi
  • 247
  • 1
  • 3
  • 13
3

I figured this out ...

The scrollView worked perfectly in an isolated env ( a brand new project ) ...

I thought the issue could be in the container of that scrollview ... and I found that the parent component has also a ScrollView ... once i removed it, everything worked perfectly.

Hend El-Sahli
  • 6,268
  • 2
  • 25
  • 42
0

React Native docs say:

Note: The weird function signature is due to the fact that, for historical reasons, the function also accepts separate arguments as an alternative to the options object. This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED.

Maybe try scrollToOffset method, if you are also using FlatList with ScrollView?

Irem
  • 43
  • 1
  • 8
  • 1
    Thank you but this is a warning not to use old signature of scrollTo (x, y, animation) ... we should use scollTo({ x: 5, y: 5, animated: true }) ... and that's what im currently using.... and the code in my question doesn't throw any error or even a warning – Hend El-Sahli Mar 23 '19 at 17:49
  • I see. Have you checked [this question](https://stackoverflow.com/questions/33208477/react-native-android-scrollview-scrollto-not-working) to see if this is similar?? – Irem Mar 23 '19 at 17:53
  • 1
    yes I did my own research before posting ... and I came across this stackoverflow post ... tried everything in it ... didn't work as well ... but thank u anyway – Hend El-Sahli Mar 23 '19 at 18:00