MA_Dev
MA_Dev

Reputation: 151

Using preventDefault with a custom hook in react

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.

Here is the link

Any help would be appreciated it.

Thanks

Upvotes: 3

Views: 8728

Answers (4)

ZaO Lover
ZaO Lover

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

Jayce444
Jayce444

Reputation: 9063

There were a few problems:

  1. You were calling the 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 there
  2. You were using the validity hook in App.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
  3. You closed the <form/> early, so there was a syntax error

Have 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

Rico AW
Rico AW

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

Kirill Skomarovskiy
Kirill Skomarovskiy

Reputation: 1575

pass handleSubmit function to the form as onsubmit

<form onSubmit={handleSubmit}>

Upvotes: 1

Related Questions