0

I am using the mui box react component with the component property set to form and an onSubmit set to the submit handler I need to trigger. I have a submit button at the end of the form. Whenever I click on the submit button it seems as if the form is submitting a get request as I see the form fields in the querystring but I am not seeing the submit handler get called. I added the e.preventDefault() in the handler and added a console.log and a debugger statement, none of which are ever reached. Also, the onChange handler I have on the textFields are not getting called either. What could be causing this to happen?

handler:

const submitForm = (e) => {
    e.preventDefault();
    console.log('We made it to the expected place.');
    debugger;
  }

Form:

<div>
        <div className="w-100">
          <Container>
            <h1 className="text-center">Login</h1>
            <Box className="card loginUI" component="form" autoComplete="off" onSubmit={submitForm}>
              <div className="card-body">
                <div className="formFlexContainer">
                  <div className="formInput">
                    <TextField className="w-100" id="userName" label="Username" variant="standard" name="userName" onChange={e => {console.log('text change 1'); setUsername(e.target.value)}}/>
                  </div>
                  <div className="formInput">
                    <TextField className="w-100" id="password" label="Password" variant="standard" name="password" onChange={e => {console.log('text change 2'); setPassword(e.target.value)}}/>
                  </div>
                  <div className="formInput d-flex justify-content-end">
                    <Button type="submit">
                      Login
                    </Button>
                  </div>
                </div>
              </div>
            </Box>
          </Container>
        </div>
      </div>
user1790300
  • 2,143
  • 10
  • 54
  • 123
  • Hey, so the onSubmit for a button only works if you have a `
    ` component. Read the documentation to clear it up
    – Sampurna Jan 03 '22 at 07:39
  • The mui Box component with the "component="form"" adds a form component. When I look at the source, I am seeing a form element. – user1790300 Jan 03 '22 at 17:31

2 Answers2

2

you should add form tag in the parent element and and add onSubmit attribute to that ,

<form onSubmit={formik.handleSubmit}>
...
</form>

in this case , i used formik , but its not matter , you should add form , or you can delete type=submit from button and set onClick for button directly

tmohammad78
  • 177
  • 2
  • 17
0

I found the solution on this stackoverflow link: js events not firing in webpack built react application. The issue was an extra reference to the bundle.js file that webpack was already adding by default. Removed and the events began working.

user1790300
  • 2,143
  • 10
  • 54
  • 123