Search code examples
javascriptreactjskeyboard

React - Calling a specific function when 'Enter' key is pressed


Didn't succeed in using this thread to help. I have button div with an onClick that invokes a handleSendMessage.

I want this handleSendMessage to be invoked whenever a user presses the 'Enter' key while on the page. How can I do that?

Component looks like this :

    const ChatScreen = () => {
      const [message, setMessage] = useState("");
      const dispatch = useDispatch();
      let chatsFromState = useSelector(state => state.chatsState.chats);

      const socket = io("localhost:4000");

      socket.on("RECEIVE_MESSAGE", msgReceived => {
        console.log("msgReceived ", msgReceived);
      });

      const handleChange = e => setMessage(e.target.value);

      const handleSendMessage = async () => {
        socket.emit("SEND_MESSAGE", message);
        await dispatch(sendMessage(message));
        setMessage("");
      };

      return (
        <div className="chatScreen">
          <div className="">HI</div>
          <input
            value={message}
            onChange={handleChange}
            placeholder="Your message here..."
          />
          <div className="sendBtn" onClick={handleSendMessage}>
            Send
          </div>
          <div className="messagesContainer">
            {chatsFromState.map((chat, i) => (
              <div className="messageBox" key={i}>
                message : {chat.message}
              </div>
            ))}
          </div>
        </div>
      );
    };

    export default ChatScreen;

Solution

  • Adding a onKeyPress keyboard event to your input element you could capture the key event and then check for the key Enter.

    The event happens in the input since this is where the user has focus, if the user clicked anywhere else on the page, the focus would be lost and this won't work anymore. The trick here is thinking where the focus might be and listen to that.

    Here is a very retrieved example, just be sure to focus on the input and hit Enter, a message will be logged:

    const ChatScreen = () => {
      const handleChange = (e) => {
        if (e.key === 'Enter') {
          console.log('setMessage');
        }
      }
    
      return (<input type="text" onKeyPress={handleChange} />);
    }
    
    const root = document.getElementById('container')
     
    ReactDOM.render(<ChatScreen />, root)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    
    <div id="container"></div>