How to trigger button onclick event on Enter key press in React

Last updated on May 30, 2021 by Suraj Sharma



In this tutorial, you’ll learn a way to simulate a button click on press of Enter key in React.

Suppose you want to submit a form on press of Enter key in the <input> field without click the submit button

Let’s create a simple <LoginForm /> function component in React.


import React from 'react';

const LoginForm = () => {
  
  const [formValue, setformValue] = React.useState({
    email: '',
    password: ''
  });

  const handleSubmit = () => {
    if (formValue.email && formValue.password) {
      console.log(Form submitted).
    }
  };

  return (
    <div>
      <p>Login Form</p>
      <input
        type="email"
        name="email"
        placeholder="enter an email"
        value={formValue.email}
      />
      <input
        type="password"
        name="password"
        placeholder="enter a password"
        value={formValue.password}
      />
      <button onClick={handleSubmit}>
        Submit
      </button>
    </div>
  );
};

Instead of clicking the Submit button to call the handleSubmit() event handler, we can use the onKeyPress event of the input field to simulate the button onClick event.

Now, define a new event handler handleKeyPress, which contains the logic to submit the form on Enter key press


import React from 'react';

const LoginForm = () => {
  
  const [formValue, setformValue] = React.useState({
    email: '',
    password: ''
  });

  const handleSubmit = () => {
    if (formValue.email && formValue.password) {
      console.log(Form submitted).
    }
  }

  const handleKeyPress = (event) => {
    // look for the `Enter` keyCode
    if (event.keyCode === 13 || event.which === 13) {
      handleSubmit()
    }
  }

  return (
    <div>
      <p>Login Form</p>
      <input
        type="email"
        name="email"
        placeholder="enter an email"
        value={formValue.email}
        onKeyPress={handleKeyPress}
      />
      <input
        type="password"
        name="password"
        placeholder="enter a password"
        value={formValue.password}
        onKeyPress={handleKeyPress}
      />
      <button>
        Submit
      </button>
    </div>
  )
};


Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.