🎓 A1Learner
🔍
0 of 50 lessons completed

Handling Submit

Handling submit runs code when a form is sent. The submit event fires when the send button is pressed.

Stop the reload

The handler stops the reload before it logs the message.

function handleSubmit(e) {
  e.preventDefault();
  console.log('Sent.');
}
return <form onSubmit={handleSubmit}><button type="submit">Send</button></form>;

A form with an input

The submit handler stops the reload and keeps the typed text.

const [name, setName] = useState('');
return <form onSubmit={(e) => e.preventDefault()}><input value={name} onChange={(e) => setName(e.target.value)} /></form>;

Example

import { useState } from 'react';

export default function App() {
  const [name, setName] = useState('');
  const [sent, setSent] = useState(false);

  function handleSubmit(e) {
    e.preventDefault();
    setSent(true);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input value={name} onChange={(e) => setName(e.target.value)} />
      <button type="submit">Send</button>
      {sent && <p>Sent.</p>}
    </form>
  );
}

Key points

  • A form element wraps the inputs and the send button.
  • The onSubmit event runs when the form is sent.
  • The preventDefault method stops the page from reloading.
  • The handler reads the state values and acts on them.
  • A button with type submit sends the form.

In this example, the name state value holds the typed text. The sent state value starts as false. The submit handler stops the reload and sets sent to true. The first render shows the input and the Send button. After a submit, the Sent message appears.

Note

Without preventDefault the page reloads and the state is lost.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Why does a submit handler call preventDefault?