B. Godoak
B. Godoak

Reputation: 305

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

Upvotes: 1

Views: 8264

Answers (2)

Konstantin Melekhin
Konstantin Melekhin

Reputation: 66

You can also use the functional component and the hook useState, useEffect.

import React, { useState, useCallback, useEffect } from "react";
import {
  Keyboard,
  ScollView,
  View,
} from "react-native";


const MyComponent = () => {
  const [scrollEnabled, setScrollEnabled] = useState(false);
  
  const keyboardDidShow = useCallback(() => {
    // show keyboard
    setScrollEnabled(false);
  }, []);

  const keyboardDidHide = useCallback(() => {
    // hide keyboard
    setScrollEnabled(true);
  }, []);

  useEffect(() => {
    const keyboardDidShowListener = Keyboard.addListener(
      "keyboardDidShow",
      keyboardDidShow
    );
    const keyboardDidHideListener = Keyboard.addListener(
      "keyboardDidHide",
      keyboardDidHide
    );

    return () => {
      keyboardDidShowListener.remove();
      keyboardDidHideListener.remove();
    };
  }, []);

  return (
    <ScrollView scrollEnabled={scrollEnabled}>
      <View />
    </ScrollView>
  );
}

Upvotes: 0

JainZz
JainZz

Reputation: 612

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>
    );
  }
}

Upvotes: 4

Related Questions