Search code examples
react-native

Auto growing text input with multiline in react native


I created a custom component which includes a TextInput and Icon inside a View. I want to grow my view height when the TextInput has multilines. This is my component. How can I achieve this?

import React from "react";
import { View, TextInput, StyleSheet } from "react-native";
import { InputIcon } from "../";

const commentInput = props => (
  <View style={styles.inputContainer}>
    <TextInput
      {...props}
      underlineColorAndroid="transparent"
      style={[
        styles.input,
        { fontSize: props.fontSize },
        props.style,
        !props.valid && props.touched ? props.invalidInput : null
      ]}
    />
    <InputIcon
      name="upload"
      size={30}
      color="gray"
      onPress={props.onPress}
      disabled={props.disabled}
    />
  </View>
);

const styles = StyleSheet.create({
  inputContainer: {
    flexDirection: "row",
    alignSelf: "center",
    width: "96%",
    marginLeft: 2,
    marginRight: 2,
    marginBottom: 10,
    height: 50,
    borderRadius: 50,
    backgroundColor: "transparent",
    borderWidth: 1,
    borderColor: "gray"
  },
  input: {
    width: "90%",
    textAlign: "center",
    color: "gray"
  },
  icon: {
    marginTop: 18,
    paddingRight: 5
  }
});

export default commentInput;


Solution

  • You can combine multiline with minHeight prop to achieve this effect.

    The relevant code would be

    <TextInput
         multiline //... to enable multiline
    
    <InputIcon
         style={{alignSelf: 'center'}} //... Should be self centered
    
    inputContainer: {
            marginTop:100,
            flexDirection: "row",
            alignSelf: "center",
            width: "96%",
            marginLeft: 2,
            marginRight: 2,
            marginBottom: 10,
            minHeight: 50, //... For dynamic height
            borderRadius: 50,
            backgroundColor: "transparent",
            borderWidth: 1,
            borderColor: "gray",
            paddingLeft: 10, //... With respect to the min height, so that it doesn't cut
            paddingTop: 10, //... With respect to the min height, so that it doesn't cut
            paddingBottom: 10 //... With respect to the min height, so that it doesn't cut
        },