Home > Mobile >  react-native-gifted-chat How to send on pressing return
react-native-gifted-chat How to send on pressing return

Time:02-22

How do I make the return button on the mobile keyboard send the message instead of creating a new line? I tried using onSubmitEditing in the textInputProps but couldn't get it to work.

CodePudding user response:

You need to implement your own ChatComposer and pass the onSubmitEditing prop in the textInputProps in there. In order to prevent keyboard dismiss you also need to set blurOnSubmit to false.

const [messages, setMessages] = useState([])


const onSend = useCallback((messages = []) => {
    setMessages((previousMessages) => GiftedChat.append(previousMessages, messages))
}, [])

const ChatComposer = (
    props: ComposerProps & {
      onSend: SendProps<IMessage>["onSend"]
      text: SendProps<IMessage>["text"]
    }
) => {
    return (
      <Composer
        {...props}
        textInputProps={{
          ...props.textInputProps,
          blurOnSubmit: false,
          multiline: false,
          onSubmitEditing: () => {
            if (props.text && props.onSend) {
              props.onSend({ text: props.text.trim() }, true)
            }
          },
        }}
      />
    )
 }

return (
    <GiftedChat messages={messages} onSend={onSend} renderComposer={ChatComposer} />
  )

If you want to remove the default send button from the text input field on the right, you need to pass a custom renderSend button, which could be empty, e.g.

renderSend={() => {}}

Notice, that I have tested all of the above on iOS only. Android might behave differently.

  • Related