levensta
levensta

Reputation: 327

How to stop reloading page after submit in the react-hook-form?

I use the react-hook-form library to validate my forms, but I want my page not to reload after submitting the form so that I can redirect the user to the desired page on my own. For example, using the navigate hook from the react-router-dom library. How to stop page reloading?

My code:

import React from 'react';

import {signInWithEmailAndPassword, updateCurrentUser} from "firebase/auth";
import {auth} from "../firebase";

import {Link, useLocation, useNavigate} from "react-router-dom";
import styles from "./elements.module.css";
import {SubmitHandler, useForm} from "react-hook-form";
import {IAuthFormFields} from "../types";
import cn from "classnames";

type locationState = { from: string };

const SignIn = () => {
  const navigate = useNavigate()
  const location = useLocation();
  const fromPage = (location.state as locationState)?.from ?? '/';
  const {
    register,
    formState: { errors },
    handleSubmit,
    setError
  } = useForm<IAuthFormFields>({
    mode: 'onBlur'
  });

  const handleLogin: SubmitHandler<IAuthFormFields> = ({email, pass}) => {
    signInWithEmailAndPassword(auth, email, pass)
      .then(async (userCredential) => {
        const {user} = userCredential;
        await updateCurrentUser(auth, user);
        navigate(fromPage);
      });
  }

  return (
    <form onSubmit={handleSubmit(handleLogin)}>
      <fieldset className={"flex flex-col items-center"}>
        <h1 className={"text-2xl font-medium"}>Sign In</h1>
        <div className={"flex flex-col w-full my-3"}>
          <input
            type="email"
            {...register('email', {
              required: true,
              pattern: {
                value: /^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/,
                message: 'Invalid email'
              }
            })}
            placeholder="Email"
            className={cn(styles.input, "my-3")}
          />
          {errors?.email && <span className={styles.msg_error} >{errors.email.message}</span>}
          <input
            type="password"
            {...register('pass', {
              required: true,
            })}
            placeholder="Password"
            className={cn(styles.input, "my-3")}
          />
          {errors?.pass && <span className={styles.msg_error} >{errors.pass.message}</span>}
          <button className={cn(styles.btn, "my-3")} >
            Sign In
          </button>
        </div>
      </fieldset>
    </form>
  );
};

export default SignIn;

Upvotes: 7

Views: 14110

Answers (6)

halilenesozdemir
halilenesozdemir

Reputation: 1

React Hook Form internally use event.preventDefault. So, adding e.preventDefault won't work.

React Hook Form Source Codes

Upvotes: 0

Nevin
Nevin

Reputation: 3298

The accepted answer types are not entirely accurate. I had some typescript errors.

This fixed it for me:

 const handleLogin = (
    data: dataType,
    e?: React.BaseSyntheticEvent // This one specifically.
  ) => {
    e?.preventDefault();     // Stop page refresh
    console.log('debug data ->', data);
  };

By calling the onSubmit event on the form like so:

<form onSubmit={handleSubmit(handleGiftCardSubmit)}>

Upvotes: 2

inkrot
inkrot

Reputation: 525


You have this handler, just take the event as the 2nd argument, this one:

const handleLogin: SubmitHandler<IAuthFormFields> = ({email, pass}) => {....

Will turn into this:

const handleLogin: SubmitHandler<IAuthFormFields> = ({email, pass}, e?: Event) => {    
 e.preventDefault()
 signInWithEmailAndPassword(auth, email, pass)
              .then(async (userCredential) => {....

Upvotes: 5

Abdur Rahman Talha
Abdur Rahman Talha

Reputation: 9

add event.preventDefault(); on the handleLogin function :) oh and you also need a event parameter

Upvotes: -1

Hans Murangaza DRCongo
Hans Murangaza DRCongo

Reputation: 860

And try to use at the begining of your handleSubmit function :

e.preventDefault() 

Upvotes: -1

Uday Shankhar
Uday Shankhar

Reputation: 7

pass e as a parameter in form onSubmit function and inside that function write

e.preventDefault();

Upvotes: -1

Related Questions