1
votes

I have a chat component with a textarea that allows to send a message when the key "enter" is pressed. It works, but the textarea is not fully reset. Its value is empty, but there is a new empty line, which hampers the placeholder to be displayed.

Here is the code:

  const [newMessage, setNewMessage] = useState("");

  const onSendMessage = () => {
    if (newMessage.length > 1) {
      onSend(newMessage);
      setIsWritting(false);
      setNewMessage("");
    }
    return undefined;
  };

 const onPressEnter = ({ key }) => {
   if (key === "Enter") {
     onSendMessage();
     return false;
   }
 };

useEffect(() => {
  document.addEventListener("keydown", onPressEnter);
  return () => document.removeEventListener("keydown", onPressEnter);
}, [onPressEnter]);

I wrote return false in onPressEnter based on this thread: Clear textarea input after enter key press. I have also tried to add the event so as to block the default behavior of adding a new blank line, but with no success so far.

How to fix this?

Also is there a way to only listen to "enter" keydown event instead of globally listening to all keys?

2

2 Answers

0
votes

No need for addEventListener you can add your event at the level of your textarea directly. And I put onKeyUp instead of onKeyDown since the second will run before the input is changed, it will not have big effect in your case but just keep in mind that they aren't the same.

<textarea onKeyUp={onPressEnter}></textarea>
0
votes

Please refer to my changes about your uploaded code here: https://codesandbox.io/s/stackoverflowcomquestions65506172-ozenl

Several changes:

  1. The input textarea component can be a controlled component so that we can easily clear the value.
  2. We can use component-wise React keyboard events instead of global event binding.
  3. Use event.preventDefault() to prevent Enter behavior being handled, in your case prevent the new line.