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(e.target.value) } /><br />
  <input type='password' value={password} onChange={(e) => setPassword(e.target.value) }
    onKeyDown={(e) => {
      if (e.key === 'Enter') { doPasswordLogin(email, password) }
    }}
  /><br />
  <Btn onClick={() => doPasswordLogin(email, password)}>Password Login</Btn>
</F>
  

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')
request.post = jest.fn()

describe("PasswordLogin", () => {

  it("current - submits on Enter", () => {
    let component = mount()
    expect(component.find('input[type="password"]').length).toEqual(1)

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

})

Leave a Reply

Your email address will not be published.

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