Buy @ Amazon

Submit a form with Enter key in React

Imagine you  have a simple form like the one shown in the below screenshot:

It is evident that there is an input text and button put in a modal dialog and the react.js code would look something like below:

However, to improve the user experience you would want the form to be submitted with a simple "Enter/Return" key press. How would you go about doing this?

The technique is to wrap around the the form elements in a form element like below:
Observe closely and you'll notice the below changes:
  • form element becomes the wrapper.
  • onClick event handler is removed from button and is pushed as onSubmit event handler of the wrapped-up form element.
  • button type is changed to submit.
If you are looking for code to play with on this, feel free to check out the open-sourced code project, titled - todolilst-react - in my Github.