1

I have a custom multiline TextInput which grows/expands automatically to fit its content:

    import React, { useState } from 'react'
    import { TextInput } from 'react-native'
    
    export function MyInput() {
        const [value, setValue] = useState('Sample')
        const [height, setHeight] = useState(56)
        return (
            <TextInput
                value={value}
                onChangeText={text => {
                    setValue(text)
                }}
                onContentSizeChange={event => {
                    setHeight(Math.max(56, event.nativeEvent.contentSize.height))
                }}
                multiline
                style={{
                    padding: '16px',
                    height: height + 'px'
                }}
            />
        )

}

However if it is already expanded to multiple lines and I delete its content, onContentSizeChange does not fire and the empty lines are not removed automatically. Any way to fix this? Thanks!

Dragon33
  • 11
  • 1

1 Answers1

1

I found two ways to shrink the input:

  1. Add a border to the TextInput in the style props, e.g.:
borderWidth: 0.5, // any value is required
borderColor: "transparent"
  1. Use onChange callback instead of the onContentSizeChange in the TextInput (originally posted here):
onChange={(e) => {
  e.nativeEvent.target.style.height = 0;
  e.nativeEvent.target.style.height = `${e.nativeEvent.target.scrollHeight}px`;
}}