Missak Boyajian
Missak Boyajian

Reputation: 2245

Material UI TextField multiline, make a new line only when pressed Shift Enter

I have a chat system built in React and I am using Material UI textfield for submitting a message. I want it to function like whatsapp or telegram on the web version. On enter send the message but on shift enter, make a new line. I have this

             <TextField
                autoFocus={true}
                color={"primary"}
                multiline
                rowsMax={4}
                value={inputValue}
                fullWidth
                placeholder={"Please enter a message"}
                onChange={e => {
                  setInputValue(e.target.value);
                }}
              />

What should I add to acheive that functionality, is it easy?

Upvotes: 3

Views: 5365

Answers (2)

ADITYA PURI
ADITYA PURI

Reputation: 1

On a keyDown prop you can do it like this...

onKeyDown={(e) => {
        if (isMultiline) {
          if ((e.key === 'Enter' && e.altKey) || (e.key === 'Enter' && e.shiftKey)) {
            e.preventDefault();
            const textarea = e.target;
            const currentCursorPosition = textarea.selectionStart;
            const textBeforeCursorPosition = textarea.value.substring(0, currentCursorPosition);
            const textAfterCursorPosition = textarea.value.substring(currentCursorPosition);
            const newText = `${textBeforeCursorPosition}\n${textAfterCursorPosition}`;
            textarea.value = newText;
            textarea.setSelectionRange(currentCursorPosition + 1, currentCursorPosition + 1);
            textarea.scrollTop = textarea.scrollHeight;
          } else if (e.key === 'Enter') {
            e.preventDefault();
            handleSubmit(e);
          }
        }
      }}

Upvotes: 0

Hamidreza
Hamidreza

Reputation: 1565

Add onKeyDown prop to your TextField

onKeyDown={(e) => {
  if(e.keyCode === 13 && !e.shiftKey) {
    e.preventDefault();
    setInputValue("");
  }
}}

Upvotes: 3

Related Questions