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

Viewed 1477

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
    }
  }}
/>;
4 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

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.

This is also working code for this.

<TextField
                style={{ margin: 8 }}
                placeholder="Add a task"
                fullWidth
                margin="normal"

                inputProps={{
                  onKeyPress: (event) => {
                    if (event.key === "Enter") {
                      // write your functionality here
                      event.preventDefault();
                    }
                  },
                }}

              />

I think you can add an onChange handler. Then your Enter can be used however you want, e.g., to submit the value. Something like this:

  const [value, setValue] = React.useState<string>()

    const handleChangeText = (event: React.ChangeEvent<HTMLInputElement>) => {
      setValue(event.target.value);
    };


return (
        <TextField
          style={{ margin: 8 }}
          placeholder="Add a task"
          fullWidth
          margin="normal"

          inputProps={{
            onKeyPress: (event) => {
              if (event.key === "Enter") {
                // write your functionality here
                event.preventDefault();
              }
            },
          }}

          onChange={handleChangeText}
        />
)
Related