2

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;
asked Mar 13, 2020 at 1:53

1 Answer 1

2

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>

answered Mar 13, 2020 at 2:18
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.