Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
400 views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...