Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I reset a text area input element? (CodeSandBox linked)

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading