Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using form with MUI onSubmit method not working

I am using MUI for components. After days of painful debugging, I found out that my form isn't calling the onSubmit method while the Box component is used to wrap the form. Please find below minimal ex. Why this is happening? onClick works fine though. Isn't Box component a valid use case here. Should I be using API differently.

import { Box, Button, TextField } from '@mui/material';

export function MainForm() {

  const submitHandler = (e) => {
    console.log('submit called');
    e.preventDefault();
  }

  return (
    <div>
      <Box
        component="form"
      >
        <form onSubmit={submitHandler}>
          <TextField />
          <Button type="submit">Submit</Button>
        </form>
      </Box>
    </div >
  )
}
like image 906
garg10may Avatar asked Jul 14 '26 23:07

garg10may


1 Answers

Since you defined your Box component as a form, you have to place your onSubmit inside it.

<Box component="form" onSubmit={submitHandler}>
    <TextField />
    <Button type="submit">Submit</Button>
</Box>

You are overriding your MUI component, so the Box is already assuming itself as a form component.

Consider reading the Overriding MUI components from the MUI documentation.

like image 79
Rui Castro Avatar answered Jul 17 '26 22:07

Rui Castro