DEV Community

Saiful Bashar
Saiful Bashar

Posted on

React Native: Using KeyboardAvoidingView for Multiline TextInput

When using KeyboardAvoidingView with a single line TextInput, it looks like this:


Issue with Multiline TextInput
The issue arises when the multiline prop is added to TextInput:


Solution
The solution is to toggle the scrollEnabled property on focus using setTimeout and disable it on blur. Here is a code snippet demonstrating this:
github link

import React from "react";
import { StyleProp, Text, TextInput, View, ViewStyle } from "react-native";

export default function InputField({
  label,
  inputProps,
  containerStyle
}: {
  label: string;
  inputProps?: React.ComponentProps<typeof TextInput>;
  containerStyle?: StyleProp<ViewStyle>
}) {
  const [focused, setFocused] = React.useState(false);
  const [scrolled, setScrolled] = React.useState(true);

  return (
    <View style={containerStyle}>
      <Text style={{ marginBottom: 8 }}>{label}</Text>
      <View
        style={{
          borderWidth: focused ? 2 : 1,
          borderColor: focused ? "white" : "grey",
          borderRadius: 8,
          maxHeight: 200,
          flexDirection: "row",
          alignItems: "center",
        }}
      >
        <TextInput
          {...inputProps}
          scrollEnabled={scrolled}
          onFocus={(e) => {
            if (inputProps && inputProps.onFocus) {
              inputProps.onFocus(e);
            }
            setFocused(true);
            setScrolled(false);
            setTimeout(() => {
              setScrolled(true);
            }, 1000);
          }}
          onBlur={(e) => {
            if (inputProps && inputProps.onBlur) {
              inputProps.onBlur(e);
            }
            setFocused(false);
            setScrolled(true);
          }}
          style={{
            padding: 16,
            flex: 1,
            margin: 0,
            minHeight: inputProps?.multiline ? 100 : "auto",
          }}
          placeholderTextColor="grey"
        />
      </View>
    </View>
  );
}
Enter fullscreen mode Exit fullscreen mode

Result
After implementing the solution, the behavior is as expected:

Top comments (2)

Collapse
 
nphamvn profile image
nphamvn • Edited

thanks. I'm searching for the solution right now!

but it seemly doesn't work as expected.
1drv.ms/v/s!AhxCvnX5QzVTg8ciRHQcu7...

Collapse
 
xxb569566 profile image
xxb569566

thx,it's useful