Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value from Material UI textfield after pressing enter?

I cannot get input value with this code. I tried with onKeyUp, onKeyDown and onKeyPress but these are not worked because not return the value. Normally get value with onChange property but it triggers every entered new character.

<TextField
  style={{ margin: 8 }}
  placeholder="Add a task"
  fullWidth
  margin="normal"
  onKeyPress={(e) => {
    if (e.key === "Enter") {
      console.log("Enter key pressed");
      // write your functionality here
    }
  }}
/>;
like image 297
Supun Sandaruwan Avatar asked Oct 17 '25 03:10

Supun Sandaruwan


2 Answers

With e.target.value you can get the input value. Add e.preventDefault to avoid an unexpected behavior:

  const onKeyPress = (e) => {
    if (e.key === "Enter") {
      console.log('Input value', e.target.value);
      e.preventDefault();
    }
  }

  <TextField
     ...
     onKeyPress={onKeyPress}/>

Working example

like image 85
lissettdm Avatar answered Oct 18 '25 16:10

lissettdm


Actually, most of the time if you wish to have this behavior, you are most likely creating a form. So wrap the TextField in a form and implement the onSubmit event.

like image 31
Matthew Kwong Avatar answered Oct 18 '25 17:10

Matthew Kwong