How to disable inserting new line in multiline TextInput when enter is pressed in React Native

Viewed 1204

I want to build a chat app which is multiline TextInput and user can send the message when the enter is pressed. However it seems when the user press enter, the new line will be inserted anyway which give the user a bad experience.

I have tried How to prevent new line when enter is pressed in react-native but the new line still persists after the user hit Enter in the keyboard. I also tried to trim the text when onChangeText is fired, but it seems the new line is still inserted. I know it works when blurOnSubmit=true, but I want to keep the keyboard open when user hits enter.

2 Answers

Just add this to TextInput -> blurOnSubmit={true}

For example:

<TextInput multiline={true} numberOfLines={1} blurOnSubmit={true} />

You can check for a line break in the updated string that we get from onChangeText and accordingly update the state. By doing this, the keyboard will not get dismissed.

Snack with the implementation here

The onChangeText function should look like this.

// function to handle onChangeText
const handleTextChange = (text: string) => {
  if (text.length) {
    let checkLineBreak = /\r|\n/.exec(text[text.length - 1]);
    if (checkLineBreak) {
      console.log(
        'Execute Something which you want to when user presses the enter key'
      );
      ToastAndroid.show('Enter Pressed keyboard not dimissed', 3000);
    }
  }

  SetMessage(text.trimEnd());
};
Related