How to submit form data in React

Unlike other JavaScript libraries, React doesn’t have any special way of handling a form submission. All you need to do is specify a custom function that gets called when user clicks on the submit button or press the Enter key. You need to pass the function into the <form> element’s onSubmit prop:

<form onSubmit={ /* your function here */ }>

What do you do when the user submits the form? It all depends on where you store your form data.

Generally, React recommends you to sync your form data with the component’s internal state through Controlled Components. When the user submits the form, you take those values and send it to the back-end service that validates and stores the data.

Here’s a complete example of a basic login form in React. Notice how the handleSubmit function is passed to the onSubmit prop:

function BasicForm(){
  const [email, setEmail] = useState('')
  const handleEmailChange = event => {

  const handleSubmit = event => {
    alert(`Your state values: \n 
            email: ${email} \n 
            You can replace this alert with your process`);

  return (
    <form onSubmit={handleSubmit}>
        <label>Email address</label>
          placeholder="Enter email"
      <button type="submit">

You can play the live demo in Code Sandbox.

Essentially, you need to cancel the form submission default behavior with preventDefault() function and then describe the process you want React to do with your form.

If you keep the form data in state, then you can send the state data into the service that accepts it using an AJAX call. Put your form data in the body of the request as a JSON string:

const handleSubmit = event => {

    const url = ''
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password })
    fetch(url, requestOptions)
        .then(response => console.log('Submitted successfully'))
        .catch(error => console.log('Form submit error', error))

You may even validate the data using an interactive form method before submitting it.

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.