React & Redux: Adding a Handler for 'Enter Key' Events

I have been working on the React and Redux series of projects. I recently passed the “Manage State Locally” exercise; however, I would like to enhance the functionality of the code I have so far by adding an event handler that will detect an enter key press and trigger the click event on the “Add message” button.

Pen on CodePen

In past projects, I’ve simply added something like this to the code to handle “enter key press” events:

document.getElementById('idOfInputField').addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {

However, based on my Internet searches, it doesn’t appear adding IDs to React components is a good idea. This makes sense to me because the whole goal of React is to have reusable components, and if an ID is hard-coded into a JSX element, within a React component, then that functionality breaks if the component is reused.

Is there a good strategy for this with React components? I assume it’s more complicated than the vanilla JS solution, above :roll_eyes:

1 Like

Hey @Audiosyncrasy, this is a great question! I can propose a solution that does that same kind of event listening, but follows the React design concept.

What you’re trying to do is listen for the “Enter” button, which will not be triggered by onChange. You can add onKeyPress in order to listen for other keystrokes. The input would become:

<input onChange={this.handleChange} 
       value={this.state.input} />

You can then listen to those keystrokes and perform a this.submitMessage in the case that Enter is pressed:

keyPressed(event) {
  if (event.key === "Enter") {

Here’s a fork of your CodePen with those changes.


Thanks, @agbales for the response and the CodePen fork you provided! I feel like I learned quite a bit in this “extra” little exercise.

1 Like

Just to update this topic for people currently looking for this info: the keypress event has been deprecated in favour of keydown (keydown documentation) and the corresponding React prop is onKeyDown.

Won’t onKeyPress trigger for all the keys on keyboard. Isn’t there a specific event for enter button ?

it doesnt work in my code
this is mine .
could you help me finding out what the problem is