Pavel Sarygin
Pavel Sarygin

Reputation: 27

Submit button reloads the page

I am working on a login form, and I am getting a strange behavior whereby whenever I click on the 'Login' button, the page simply reloads, without logging in my email and password through the 'submitHandler' function. Below is a code of the form (I removed a lot of extra CSS formatting and div's). Here is a screenshot of the form:

loginForm

import React from 'react'
import { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { login } from "../../../actions/userActions";
import { Form, Button, Row, Col } from "react-bootstrap";

function LoginForm ({history}) {

    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

    const submitHandler = (e) => {
      e.preventDefault();
      console.log(email, password)
      // dispatch(login(email, password));
    };

   
    return (
       <form>              
              <button onSubmit={submitHandler} type="submit">
            Login
          </button>              
              </form>
 
    )
}

export default LoginForm

Does anyone have idea why the page reloads after clicking on the login button?

Upvotes: 2

Views: 417

Answers (3)

rcanpahali
rcanpahali

Reputation: 2643

You can also convert button type="" method provider submit to button, in some cases you don't really want to submit internal form so just keep in mind.

Here is the example,

<form>    
  <button onSubmit={submitHandler} type="button">
</form>

Other answer is also OK, but I would like to approach from a different angle.

Upvotes: 1

Rakhi Mishra
Rakhi Mishra

Reputation: 31

Try calling the submitHandler with onSubmit on the form instead of on the button.

Upvotes: 0

Drew Reese
Drew Reese

Reputation: 203407

Issue

The button is of type="submit" but the form has no onSubmit handler and is thus taking the default form action, i.e. submitting the form and reloading the page.

Solution

Move the onSubmit to the form element so the callback can prevent the default form action from occurring.

<form onSubmit={submitHandler}>              
  <button type="submit">
    Login
  </button>              
</form>

Upvotes: 3

Related Questions