How to prevent page refresh on form submit in React

Last updated on August 26, 2023
How to prevent page refresh on form submit in React

To prevent a page refresh on form submit in React, call event.preventDefault() in the submit event listener.

import React, { useState } from 'react';

function LoginForm() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleEmailChange = (event) => {
    setEmail(event.target.value);
  };

  const handlePasswordChange = (event) => {
    setPassword(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    
    // Simulate form submission by clearing input fields
    setEmail('');
    setPassword('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Email
        <br />
        <input
          type="email"
          value={email}
          onChange={handleEmailChange}
          required
        />
      </label>
      <br />
      <label>
        Password
        <br />
        <input
          type="password"
          value={password}
          onChange={handlePasswordChange}
          required
        />
      </label>
      <br />
      <button type="submit" style={{ marginTop: 16 }}>
        Submit
      </button>
    </form>
  );
}

export default function App() {
  return <LoginForm />;
}
The page refresh is prevented in React when the button submits the form.

We use the Event preventDefault() method to stop the default action of the event from happening. In this case, that action was a page refresh, so preventDefault() prevented the page refresh on the form submission.

const handleSubmit = (event) => {
   event.preventDefault();
   
   // Simulate form submission by clearing input fields
   setEmail('');
   setPassword('');
 };

preventDefault() is a property of an Event object, which lets us access and modify event-related data.

We use the onSubmit prop to add a submit event listener to the form; this listener runs when the user clicks the button to submit the form.

All we did here was reset the form, but of course in the real world, you probably want to make an AJAX request to a server with the form data.

const handleSubmit = async (event) => {
  event.preventDefault();

  const user = {
    email: email,
    password: password,
  };

  try {
    const response = await axios.post('http://your-api-url.com', user);
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }

  setEmail('');
  setPassword('');
};

For the button to submit the form, we must set its type prop to submit

<button type="submit" style={{ marginTop: 16 }}>
  Submit
</button>

With type="submit", the browser also submits the form when the user presses the Enter key in an input field.

Every Crazy Thing JavaScript Does

Every Crazy Thing JavaScript Does
Avoid painful bugs and save valuable time with Every Crazy Thing JavaScript Does, a captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Remove type="submit" from the button to prevent page refresh

To prevent page refresh on form submit in React, you can also remove the type="submit" from the button.

When is this useful? You may want to show an alert message or something before submission. In this case, we wouldn't want type="submit" since it submits the form on button click.

import React, { useState } from 'react';

function LoginForm() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleEmailChange = (event) => {
    setEmail(event.target.value);
  };

  const handlePasswordChange = (event) => {
    setPassword(event.target.value);
  };

  const handleSubmit = () => {
    // Perform custom actions before form submission
    alert('Are you sure you want to submit the form?');

    // Simulate form submission by clearing input fields
    setEmail('');
    setPassword('');
  };

  return (
    <form>
      <label>
        Email
        <br />
        <input
          type="email"
          value={email}
          onChange={handleEmailChange}
          required
        />
      </label>
      <br />
      <label>
        Password
        <br />
        <input
          type="password"
          value={password}
          onChange={handlePasswordChange}
          required
        />
      </label>
      <br />
      <button type="button" onClick={handleSubmit} style={{ marginTop: 16 }}>
        Submit
      </button>
    </form>
  );
}

export default function App() {
  return <LoginForm />;
}
Prevent a page refresh on form submit in React to show an alert dialog before submission.

We used type="button" on the button, but that's as good as not having a type attribute. It doesn't do anything on click.

Key takeaways

  • To prevent page refresh on form submit in React, call event.preventDefault() in the submit event listener.
  • Set type="submit" to ensure the form submits on button click or Enter press. Remove it when you don't want this.
  • Remove type="submit" when you need to do something after the button click before submitting the form, e.g., show a dialog, make an initial request, etc.

11 Amazing New Features in ES13

11 Amazing New Features in ES13
Get up to speed with all the latest features added in ECMAScript 13 to modernize your JavaScript with shorter and more expressive code.

See also