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?