react native avoid keyboard when multiline

React Native: Avoid Keyboard When Multiline

If you are building a React Native app that requires users to input text, you will likely need to manage the keyboard behavior. When using multiline text input, the keyboard can take up a lot of space on the screen, which can be inconvenient for users. In this case, it is important to ensure that the keyboard does not interfere with the user's ability to enter and edit their text.

Method 1: Using the Keyboard Avoiding View Component

The easiest way to avoid the keyboard when using multiline text input in React Native is to use the KeyboardAvoidingView component. This component automatically adjusts the position of the screen content when the keyboard is displayed, so that the text input is always visible.


import React, { Component } from 'react';
import { KeyboardAvoidingView, TextInput, StyleSheet } from 'react-native';

export default class MyComponent extends Component {
  render() {
    return (
      <KeyboardAvoidingView behavior="padding" style={styles.container}>
        <TextInput
          style={styles.input}
          placeholder="Enter text here..."
          multiline={true}
          underlineColorAndroid="transparent"
        />
      </KeyboardAvoidingView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    padding: 10,
    width: '80%',
  },
});

In this example, we are using the KeyboardAvoidingView component to wrap our TextInput component. We are also setting the behavior prop to "padding", which tells the KeyboardAvoidingView component to adjust the padding of the screen content when the keyboard is displayed. This ensures that the text input is always visible, even when the keyboard is shown.

Method 2: Using the Keyboard API

If you need more control over the keyboard behavior, you can use the Keyboard API provided by React Native. This API allows you to show and hide the keyboard programmatically, as well as get information about the keyboard's status.


import React, { Component } from 'react';
import { TextInput, StyleSheet, Keyboard } from 'react-native';

export default class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      textInputFocused: false,
    };
    this.textInputRef = React.createRef();
  }

  componentDidMount() {
    this.keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      this._keyboardDidShow,
    );
    this.keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      this._keyboardDidHide,
    );
  }

  componentWillUnmount() {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }

  _keyboardDidShow = () => {
    this.setState({ textInputFocused: true });
  }

  _keyboardDidHide = () => {
    this.setState({ textInputFocused: false });
  }

  render() {
    return (
      <TextInput
        ref={this.textInputRef}
        style={[
          styles.input,
          this.state.textInputFocused ? { marginBottom: 200 } : {},
        ]}
        placeholder="Enter text here..."
        multiline={true}
        underlineColorAndroid="transparent"
        onFocus={() => {
          this.textInputRef.current.measure((x, y, width, height, pageX, pageY) => {
            const keyboardHeight = 200;
            const inputBottomOffset = y + height - pageY;
            const distanceFromKeyboard = inputBottomOffset - keyboardHeight;
            if (distanceFromKeyboard > 0) {
              this.setState({ textInputFocused: true }, () => {
                this.scrollRef.current.scrollTo({ y: distanceFromKeyboard });
              });
            }
          });
        }}
        onBlur={() => {
          this.setState({ textInputFocused: false });
        }}
      />
    );
  }
}

const styles = StyleSheet.create({
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    padding: 10,
    width: '80%',
    minHeight: 100,
  },
});

In this example, we are using the Keyboard API to manually control the keyboard behavior. We are also adding some extra functionality, such as automatically scrolling the screen when the text input is focused and the keyboard is displayed.

First, we are creating a ref for our TextInput component using the React.createRef() function. We are also setting up listeners for the keyboardDidShow and keyboardDidHide events using the Keyboard.addListener() function. These listeners will update the state of our component when the keyboard is shown or hidden.

Next, we are setting up some additional functionality for our TextInput component. We are using the onFocus() and onBlur() props to detect when the text input is focused or blurred. When the text input is focused, we are using the measure() function to get the position and dimensions of the text input. We are then calculating the distance between the bottom of the text input and the top of the keyboard, and scrolling the screen if necessary to ensure that the text input is still visible.

Overall, both of these methods can be used to avoid the keyboard when using multiline text input in a React Native app. The KeyboardAvoidingView component is generally easier to use, while the Keyboard API provides more control over the keyboard behavior.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe