I am building a form using React and MUI. I want to prevent the form from being submitted when the user presses the enter key. Normally I would do that with e.preventDefault()
, but somehow that doesn't work. I think it has something to do with the TextField
component from MUI.
Here is a simple example for my form and here is
function MyForm() {
return (
<form onSubmit={(e) => {
e.preventDefault()
/* do submit stuff here */
}}>
<TextField id="outlined-basic" label="Outlined" variant="outlined" />
<Button type='submit'>Submit</Button>
</form>
);
}
Am I doing something wrong here?
CodePudding user response:
preventDefault function in onSubmit of form, prevents the page from being reloaded, and basically you need to write another preventDefault inside of the textfield as below:
<TextField
onKeyPress={e => e.key === 'Enter' && e.preventDefault()}
/>