4

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 4

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

after putting onKeyPress={onKeyPress} property it doesn't trigger exactly. Because it is not a property of material UI textfield API. material-ui.com/api/text-field/#textfield-api I tried with this answer but it doesn't work when getting value.
@SupunSandaruwan Did you check the working example? according to the component implementation it receive other props, and onKeyPress is a synthetic event, see github.com/mui-org/material-ui/blob/next/packages/material-ui/… take a look at how ...others are attached to TextFieldRoot
thank you very much for your explanation and answer. I got new thing.
2

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.

Comments

1

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(); } }, }} /> 

Comments

0

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} /> ) 

1 Comment

onChange is triggering when everytime that i entering character. I want trigger function only after pressing enter button.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.