3

How can I change the bool value of scrollEnabled param of React Native ScrollView when scrolling reaches a certain position?

I do have a ScrollView inside a ScrollView, and the inner ScrollView doesn't respond because of the outer ScrollView. Inner ScrollView works when scrollEnabled param is set to False of outer ScrollView. My idea is to dynamically set outer ScrollView to scrollEnabled={false} when reaches at the bottom. How do I do this.

Thanks,

nabeel
  • 1,181
  • 2
  • 10
  • 24

3 Answers3

10

There are two ways to accomplish this. The first one, as described by @binchik, is to set scrollEnabled to a state variable and update the state when necessary. Of course, this triggers a re-render, which can be problematic. The second way is to update the prop on the ScrollView component directly without re-rendering. You can do it like this:

class DisableScrollWithoutRerender extends React.Component {
  listRef = React.createRef();
  ...
  render() {
    return <ScrollView ref={this.listRef} />;
  }

  disableScroll() {
    const { current: list } = this.listRef;
    list.setNativeProps({ scrollEnabled: false });
  }
}

Personally I would recommend to stick to the first option when a re-render is affordable and avoid the second one unless it's exactly what you need.

dols3m
  • 1,676
  • 2
  • 16
  • 25
  • 1
    You can find more details [here](https://facebook.github.io/react-native/docs/direct-manipulation). – dols3m Sep 18 '18 at 22:37
  • 1
    I'm aware that this answer is 1.5 years late, but perhaps it will be helpful to someone who stumbles upon this question in the future. – dols3m Sep 18 '18 at 22:37
  • 3
    I had to use `this.listRef.setNativeProps({ scrollEnabled: false });` instead of `disableScroll()` – dǝɥɔS ʇoıןןƎ Oct 04 '18 at 12:23
  • 1
    I would use this solution when you need scrolling to be disabled immediately. For example, when starting a drag-n-drop for something embedded in a scrollview. – Florian Segginger Nov 18 '19 at 15:31
1

Provide a ref to your scrollview/listview. and then use following to change scrollEnabled value.

render() {
  return <ScrollView ref="scrollView" />;
}

onSomeEvent() {
  this.refs.scrollView.setScrollEnabled(true); // will enable scroll
}
Victor
  • 4,171
  • 1
  • 29
  • 37
0

ScrollView component has a prop callback function onScroll: ({nativeEvent: {contentOffset: {y}}, contentSize: {height}}).

So you could have a scrollEnabled variable in your state. and set it to true if the contentOffset.y is equal to or more than the contentSize.height and false otherwise.

Make sure that you do not make unnecessary setState calls. Since it will make the component rerender every time even if the previous state is exactly the same to the new one.

binchik
  • 909
  • 8
  • 10