Home > Back-end >  How can I reset a text area input element? (CodeSandBox linked)
How can I reset a text area input element? (CodeSandBox linked)

Time:08-09

Link to codesandbox: https://codesandbox.io/s/xenodochial-knuth-4k4ys7?file=/src/App.js

I am trying to figure out exactly how I can reset a textarea back to its original state with the placeholder text. The best I have so far is the following;

//Created ref to clear after keydown
  const inputRef = React.useRef(null);

  return (

      <Input
        ref={inputRef}
        as="textarea"
        placeholder="this text box should clear after an enter press"
        style={{ height: "300px" }}
        onKeyDown={(e) => {
          if (e.code === "Enter") {
            inputRef.current.value = "";
          }
        }}
      />
  );
}

Thankyou, all help is appreciated!

CodePudding user response:

You can add e.preventDefault() which would help to prevent adding a new character after populating your state data.

<Input
        ref={inputRef}
        as="textarea"
        placeholder="this text box should clear after an enter press"
        style={{ height: "300px" }}
        onKeyDown={(e) => {
          if (e.code === "Enter") {
            setData(inputRef.current.value);
            inputRef.current.value = "";
            //prevent adding a new character
            e.preventDefault();
          }
        }}
      />

Sandbox

  • Related