onSubmit not working for text input with multiline

Viewed 1086

I'm using a texfield which clears the input text typed when enter key is pressed it triggers the onSubmit function, but for some reason when Multline is set to true, the onSubmit doesn't work.

import React, { useRef } from "react";
import "./styles.css";
import TextField from "@material-ui/core/TextField";

export default function App() {
  const inputRef = useRef();

  const addMessage = e => {
    inputRef.current.value = "";
  };
  return (
    <form onSubmit={addMessage}>
      <TextField
        // multiline="true"
        inputRef={inputRef}
        multiline="true"
        id="filled-basic"
        label="Filled"
        variant="filled"
      />
    </form>
  );
}

I added a codesandbox as well which has the code to make it easier https://codesandbox.io/s/nifty-morning-w2gqx

2 Answers

As per material ui's multiline doc:

The multiline prop transforms the text field into a textarea or a TextareaAutosize

  1. Provide a boolean value to multiple prop

  2. In order to submit form upon enter key press, provide an onKeydown like below.

  3. To auto resize after form submit, you can use ref and set the height to auto.

export default function App() {
  const inputRef = useRef();

  const addMessage = e => {
    console.log("hi");
    inputRef.current.getElementsByTagName("textarea")[0].value = "";
  };

  const handleKeyDown = event => {
    if (event.which === 13) {//<------use enter key to submit form
      inputRef.current.getElementsByTagName("textarea")[0].style.height = "auto"; //<------resize text area
      addMessage(event);
      event.preventDefault();
    }
  };

  return (
    <form onSubmit={addMessage}>
      <TextField
        ref={inputRef}
        multiline //<-----see here
        onKeyDown={handleKeyDown} //<-----see here
        id="filled-basic"
        label="Filled"
        variant="filled"
      />
    </form>
  );
}

working demo

Note: You can also consider to submit form upon shift + enter key (not just enter). This way, user can hit enter to type text in the next line of the text area.(better user experience)

//use shift + enter key to submit form
if (event.keyCode === 13 && event.shiftKey) {
 ...
}

Material UI component TextField takes a boolean value for multiline. Either set multiline={true} or just include multiline as in:

<TextField
  inputRef={inputRef}
  multiline
  id="filled-basic"
  label="Filled"
  variant="filled"
/>

For more information see: https://material-ui.com/components/text-fields/#multiline

Related