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
}
}}
/>;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With