Mark As Completed Discussion

Form Submission

After capturing and validating user input in a form, the next step is to submit the form data to a server for further processing. This is a crucial part of working with forms in React, as it allows you to interact with backend services and update the application's state based on the response.

Handling Form Submission

To handle form submission in React, you need to attach an event handler function to the form's onSubmit event. This function will be triggered when the user clicks the submit button or presses the enter key.

When the form is submitted, you can access the form data, such as the values of input fields, using references or state management libraries like Redux or MobX. Once you have the form data, you can make an HTTP request to the server using techniques like AJAX or the Fetch API.

Here's an example of handling form submission in React:

JAVASCRIPT
1import React, { useState } from 'react';
2
3const Form = () => {
4  const [formData, setFormData] = useState({ name: '', email: '' });
5
6  const handleSubmit = (event) => {
7    event.preventDefault();
8
9    // Make an HTTP request to submit form data
10    fetch('/api/submit-form', {
11      method: 'POST',
12      body: JSON.stringify(formData),
13      headers: { 'Content-Type': 'application/json' },
14    })
15      .then((response) => response.json())
16      .then((data) => {
17        // Handle the response from the server
18        console.log(data);
19      })
20      .catch((error) => {
21        // Handle any errors
22        console.error(error);
23      });
24  };
25
26  const handleChange = (event) => {
27    setFormData({
28      ...formData,
29      [event.target.name]: event.target.value,
30    });
31  };
32
33  return (
34    <form onSubmit={handleSubmit}>
35      <div>
36        <label htmlFor='name'>Name:</label>
37        <input type='text' id='name' name='name' value={formData.name} onChange={handleChange} />
38      </div>
39      <div>
40        <label htmlFor='email'>Email:</label>
41        <input type='email' id='email' name='email' value={formData.email} onChange={handleChange} />
42      </div>
43      <button type='submit'>Submit</button>
44    </form>
45  );
46};
47
48export default Form;

In the example above, we have a form component that captures the user's name and email address. When the form is submitted, an HTTP POST request is made to the /api/submit-form endpoint with the form data as the request body. The response from the server is logged to the console.

Handling form submission in React involves processing user input, making HTTP requests, and handling server responses. It's an important part of building interactive and data-driven web applications.