Home > other >  React: check the pressed key on form submit
React: check the pressed key on form submit

Time:02-13

I am using React (and Material UI), and I am trying to submit a form. As default by pressing enter when focused on the text field, the form submits. I want it to only happen when I press the Submit button.

The form

<Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}>
    <TextField
        margin="normal"
        required
        fullWidth
        id="title"
        label="Title"
        name="title"
        autoComplete="title"
        autoFocus
        defaultValue={title}
    />
    <TextArea setData={setData} data={JSON.parse(description)} />
    <Button
        type="submit"
        fullWidth
        variant="contained"
        sx={{ mt: 3, mb: 2 }}
    >
        Finish
    </Button>
    <Link href="/">
        Back
    </Link>
</Box>

The submit function

 const handleSubmit = async (e) =>
    {
        e.preventDefault();
        console.log(e)
        //
    }

CodePudding user response:

This is default behavior since you have your code in a form. It shouldn't matter to you where the users cursor is. This is necessary for screen readers and for basic user experience.

To focus on the next field, the user should be able to tab to the next field.

e.preventDefault is to keep the page from reloading on submit.

CodePudding user response:

I just added onKeyPress to the TextField and checked if the pressed key is equal to Enter

<TextField
    margin="normal"
    required
    fullWidth
    id="title"
    label="Title"
    name="title"
    autoComplete="title"
    onKeyPress={(e) => { e.key === 'Enter' && e.preventDefault(); }} //<----
    autoFocus
/>
  • Related