Reputation: 151
I am a beginner React developer. I am trying to enhance a forms tutorial I did using hooks. I refactored the code so that the inputs and button are each a separate component. I have also refactored the hooks so that each hook is in a separate file. The problem that I am running into is the handleSubmit method in the useSubmitted custom hook (hooks/useSubmitted.js
) file. I keep getting the error TypeError: event.preventDefault is not a function
. I have tried to fix it and also looked for a solution in Google, but to no avail.
Any help would be appreciated it.
Thanks
Upvotes: 3
Views: 8728
Reputation: 433
I am just wonder why you use preventDefault function. Following your code, the parameter named event in handleSubmit function is same as submitted state in useSubmitted function component. It seems that you have misunderstanding about preventDefault function and the usage.
Please refer this article. https://github.com/ankeetmaini/simple-forms-react
Upvotes: 0
Reputation: 9063
There were a few problems:
handleSubmit
function inside the JSX. It's a hook, so it's called inside the body function and you then have access to the returned values thereApp.js
, but in reality you use that inside the submitted one, since it shouild only submit if it's valid. So you don't need it in App.js
<form/>
early, so there was a syntax errorHave a look at the changes in this sandbox, specifically the ones inside App.js
. Should have the necessary fixes.
As a side note, the way these hooks are laid out doesn't quite make sense. The validity and the submission of the form should be together, as they are co-dependent. Having separate hooks doesn't quite make sense. The form values dictate the validity, and the validity determines the ability to submit.
Upvotes: 0
Reputation: 59
handleSubmit need parameter with type event and you give it submitted which has type boolean. You can get type event.preventDefault() from
<form onSubmit={handleSubmit} />
or
<form onSubmit={(event) => handleSubmit(event)} />
Upvotes: 3
Reputation: 1575
pass handleSubmit function to the form as onsubmit
<form onSubmit={handleSubmit}>
Upvotes: 1