Search code examples
react-nativekeyboardscrollview

React Native enable/disable ScrollView when Keyboard appear/hide


I want to disable scroll when keyboard is hidden and enable when keyboard appear.

Any help will be appreciated. Thank you in advance.

React Native Version: 0.50.3


Solution

  • https://facebook.github.io/react-native/docs/keyboard.html

    There are listeners for keyboard show and hide.

    You can use these functions keyboardDidshow and keyboardDidHide for enable and disable scrollView.

    import React, { Component } from 'react';
    import { Keyboard, TextInput } from 'react-native';
    
    class Example extends Component {
      componentWillMount () {
        this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
        this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
      }
    
      state {
        toScroll: false
      }
    
      componentWillUnmount () {
        this.keyboardDidShowListener.remove();
        this.keyboardDidHideListener.remove();
      }
    
      _keyboardDidShow () {
        this.setState({ toScroll: true });
      }
    
      _keyboardDidHide () {
        this.setState({ toScroll: false });
      }
    
      render() {
        const { toScroll } = this.state;
        return (
          <ScrollView scrollEnabled={toScroll}>
            <View />
          </ScrollView>
        );
      }
    }