Categories
React Answers

How to Get Input Text Field Values When Enter Key is Pressed in React?

Spread the love

Sometimes, we want to get input text field values when enter key is pressed in React.

In this article, we’ll look at how to get input text field values when enter key is pressed in React.

Get Input Text Field Values When Enter Key is Pressed in React

To get input text field values when enter key is pressed in React, we can add an event handler for the keypress event into the input.

For instance, we write:

import React from "react";

export default function App() {
  return (
    <input
      onKeyPress={(ev) => {
        if (ev.key === "Enter") {
          ev.preventDefault();
          console.log(ev.target.value);
        }
      }}
    />
  );
}

to set the onKeyPress prop to a function that checks if the enter key is pressed by comparing 'Enter' against ev.key.

We prevent the default server side form submission behavior from happening with ev.preventDefault.

If it’s true. then we get the value that’s typed into the input box with ev.target.value.

Conclusion

To get input text field values when enter key is pressed in React, we can add an event handler for the keypress event into the input.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *