How to get the Material UI TextField value when enter key is pressed in React?

Sometimes, we want to get the Material UI TextField value when enter key is pressed in React.

In this article, we’ll look at how to get the Material UI TextField value when enter key is pressed in React.

How to get the Material UI TextField value when enter key is pressed in React?

To get the Material UI TextField value when enter key is pressed in React, we can set the onKeyPress prop of the TextField to a function that checks which key is pressed.

Then we can run the code we want when the key we’re checking for is pressed.

For instance, we write:

import { TextField } from "material-ui";
import React from "react";
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";

export default function App() {
  return (
    <MuiThemeProvider>
      <div>
        <TextField
          onKeyPress={(e) => {
            if (e.key === "Enter") {
              console.log(e.target.value);
            }
          }}
        />
      </div>
    </MuiThemeProvider>
  );
}

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

If that’s true, then we log the TextField‘s value, which is stored in e.target.value.

Conclusion

To get the Material UI TextField value when enter key is pressed in React, we can set the onKeyPress prop of the TextField to a function that checks which key is pressed.

Then we can run the code we want when the key we’re checking for is pressed.