I’m looking into React and React Hook Form, I managed to display custom messages below the inputs but I also want to display an alert using react-toastify
to let the user know about all the errors. How can I add a function a part from the existing error message?
I want to have something like errors && callMyFunction()
.
2
Answers
I went through the React Hook Form docs and I realised the
errors
property of theformState
returns an object and not an array (https://react-hook-form.com/docs/useform/formstate). Therefore, If you want to trigger a toast whenever there is an error, then you can just achieve this with theuseEffect
hook using this reproducible code I have written:I hope this solves it for you.
The function
handleSubmit
receives two parameters:onValid
for handling successful submissionsonInvalid
for handling errors.onInvalid
function is triggered whenever the form is submitted with errors.Here’s an example:
Then, in your form: