I am new to React. I am facing an issue while I try to handle a form submit.
Anyone knows this answer please let me know, Using React Material-UI, React-Hook-Form With the controller.
My program has 3 TextFields. Calculation: PendingTime=ActualTime-working time; actual-time is a default value (value is 5). While I change the WorkTime Text field value, Pending Time automatically updates the pending time value. I added the onChange event in the WorkTime Text field. In the OnSubmit event, I need to get the actual-time value, WorkTimeValue, and PendingTimeValue. But I was not able to get the value onSubmit.
I wrote my code in CodeSandbox.
CodePudding user response:
To answer your question, the reason why is not submitting the form is because you're not tying the Button component to the input, add this prop to your component and you'll be able to submit the form
<Button variant="contained" type="submit">Submit</Button>
the type="submit" should allow to submit the form.
Now that you have the answer, you're not using react hook form correctly, you should not mix React.useState with react-hook-form since its loses it purpose, please read the documentation on how to use the register hook with inputs and if you need to update the one of the input values, just watch for the input changes and you'll be read to go.
Also you're getting a warning because you have a form nested inside a form, so instead of using the box as a form change it to be a div or whatever that is valid html nesting:
<Box
component="div"
sx={{
"& > :not(style)": { m: 1, width: "25ch" }
}}
>
Here's a working sandbox with all the functionality you want to do: Working sandbox
This includes calculating the pending time every-time you change the actualTime and the workTime and it will submit properly, also the useState is removed since you don't need it.
CodePudding user response:
Remove your form
tag completely, and place the onSubmit handler inside the Box component.
See, you assigned its component to form
, which means you have a nested form inside your form. the submit button is inside the nested form, and onClick
does not call the onSubmit
function inside the outer form.
Some Material-Ui components accept a component
attribute, and it creates an HTML tag of that specified value.
return (
<Box
onSubmit={handleSubmit(onSubmit)}
component="form"
sx={{
"& > :not(style)": { m: 1, width: "25ch" }
}}
noValidate
autoComplete="off"
>
// ...
</Box>
);