form is not posting using react handleSubmit hook

I am trying to post this form to my mongoDB. When I just use onSubmit={true} the form posts just like I want. However, when I use the following code and return true the form does not post and I don’t know why.

const handleSubmit = (e) => {
        let password =;
        let confirmPassword =;
        let email =;
        let emailRegex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

        // set up email regex. and regex for valid names.
        if (!emailRegex.test(email)) {
            setErrorMessage("invalid email address.");
            return false;
        if (password !== confirmPassword) {
            setErrorMessage("passwords do not match.");
            return false;
        console.log("reached end")
        return true;

This is the handleSubmit function. When I take away e.preventDefault() the form posts but does not have any of the validations I want to do first.

Also I have a console.log("reached") at the end of the function that always shows and return true; right after it. Thus, the function should return true and form should post.

<Form id="registerForm" onSubmit={handleSubmit} method="POST" action="http://localhost:4000/api/auth/register">



Again when I replace handleSubmit with the boolean variable true everything works as planned. I also tried onSubmit={(e) => handleSubmit(e)} but get the same problem.

Can anyone help?

>Solution :

This happens because you’re calling e.preventDefault(); in your submit function, which prevents the default submit action from firing. So your form is going through validation but then never submits.

To submit the form, add at the end of your handleSubmit method.

Leave a Reply