How to capture Enter key in React

CategoriesHomepage, JavaScript, Node & React

Let’s say you have a couple of inputs in React, maybe a login form and you’d like the user to type in email, password, and login. Advanced users are likely to hit enter on the password field. By default, React does nothing in this case. Generally, I don’t create a <form /> element just to have a few controlled inputs. I’ve seen people do the following: (1) wrap inputs in a form, and (2) prevent default of “submit” event. I think a better solution is to register an onKeyDown event:

class Input extends React.Component {
  _handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      console.log('validate or submit');

  render() {
    return <input type="text" onKeyDown={this._handleKeyDown} />onKeyDown event:

I usually inline a javascript function that’s used only once. Here is an example of production code:

return <F>
  <input type='email' value={email} onChange={(e) => setEmail( } /><br />
  <input type='password' value={password} onChange={(e) => setPassword( }
    onKeyDown={(e) => {
      if (e.key === 'Enter') { doPasswordLogin(email, password) }
  /><br />
  <Btn onClick={() => doPasswordLogin(email, password)}>Password Login</Btn>

And of course a test because we are good people:

import Adapter from "enzyme-adapter-react-16"
import * as enzyme from "enzyme"
import { mount, shallow } from "enzyme"
import React, { useState } from "react"

import { PasswordLogin } from "./"
import { AppMock, logg, request } from "$shared"

enzyme.configure({ adapter: new Adapter() })

jest.mock('request') = jest.fn()

describe("PasswordLogin", () => {

  it("current - submits on Enter", () => {
    let component = mount()

    component.find('input[type="password"]').simulate('keydown', { key: 'Enter' })


Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.