Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native TextInput auto grow when multilne

Tags:

react-native

I want to create a TextInput which can grow automatically when it has multilines.

 <TextInput
            placeholder="Type Comment"
            value={this.state.comment.value}
            onChangeText={value => this.onChangeComment(value)}
            onPress={() => this.uploadComment()}
            multiline={true}
            maxLength={200}
            numberOfLines={5}
          />

How can I achieve this?

like image 656
Shashika Avatar asked Apr 27 '18 11:04

Shashika


People also ask

How do you expand TextInput in react native?

Use minHeight, maxHeight instead, and if multiline is enabled, the TextInput will grow till reaching the maxHeight, then will be scrollable. no calculation nor inner state needs to ba maintained. Same thing apply for minWidth, maxWidth if you need to expand widly.

What is TextInput in react native?

TextInput is a Core Component that allows the user to enter text. It has an onChangeText prop that takes a function to be called every time the text changed, and an onSubmitEditing prop that takes a function to be called when the text is submitted.


2 Answers

To implement auto grow multiline text input, you can adjust the height of the text input according to the content size in the textInput.

you can use onContentSizeChange prop in TextInput and call a function to increase/decrease the height of input.

Here is the quick example code

export default class YourComponent extends Component {

  constructor (props) {
    super(props);
    this.state = {
      newValue: '',
      height: 40
    }
  }

  updateSize = (height) => {
    this.setState({
      height
    });
  }

  render () {
    const {newValue, height} = this.state;

    let newStyle = {
      height
    }

    return (
    <TextInput
      placeholder="Your Placeholder"
      onChangeText={(value) => this.setState({value})}
      style={[newStyle]}
      editable
      multiline
      value={value}
      onContentSizeChange={(e) => this.updateSize(e.nativeEvent.contentSize.height)}
    />
    )
  }

}  

OR

You might want to use react-native-auto-grow-textinput

like image 80
Shivam Avatar answered Oct 15 '22 18:10

Shivam


With React Hooks

Just to add to Shivam's answer, here is the version with hooks:

import React, { useState } from 'react'

export default function MyTextInput(props) {
    const [height, setHeight] = useState(42)
    return <TextInput
        style={styles.input, {height: height}}
        onContentSizeChange={e => setHeight(e.nativeEvent.contentSize.height)} />
}
like image 35
Andrei Avatar answered Oct 15 '22 16:10

Andrei