Flat Preloader Icon

Handling Form Submissions

Form submissions are a crucial part of web applications, enabling users to submit data that can be processed or stored. React provides a structured way to manage form submissions by leveraging controlled components and state management.

Setting Up the Form

  1. Create a Form Component: Start by creating a form component in React.
  2. Initialize State: Use the useState hook to initialize state for form fields.
				
					import React, { useState } from 'react';

const MyForm = () => {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
  });

  return (
    <form>
      <div>
        <label htmlFor="name">Name:</label>
        <input
          type="text"
          id="name"
          name="name"
          value={formData.name}
        />
      </div>
      <div>
        <label htmlFor="email">Email:</label>
        <input
          type="email"
          id="email"
          name="email"
          value={formData.email}
        />
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

export default MyForm;

				
			

Handling Input Changes

To manage form inputs, handle changes using the handleChange function, updating the state accordingly.
				
					const handleChange = (e) => {
  const { name, value } = e.target;
  setFormData({
    ...formData,
    [name]: value,
  });
};

				
			

Handling Form Submission

Capture form submission using the handleSubmit function. Prevent the default form submission behavior and process the data as needed.
				
					const handleSubmit = (e) => {
  e.preventDefault();
  // Validate and process form data
  console.log('Form submitted:', formData);
};

return (
  <form onSubmit={handleSubmit}>
    {/* Form fields */}
    <button type="submit">Submit</button>
  </form>
);

				
			

Validation

Implement validation logic in the handleSubmit function or create a separate validation function.
				
					const validateForm = () => {
  const errors = {};
  if (!formData.name) {
    errors.name = 'Name is required';
  }
  if (!formData.email) {
    errors.email = 'Email is required';
  } else if (!/\S+@\S+\.\S+/.test(formData.email)) {
    errors.email = 'Email address is invalid';
  }
  return errors;
};

const handleSubmit = (e) => {
  e.preventDefault();
  const errors = validateForm();
  if (Object.keys(errors).length === 0) {
    console.log('Form submitted:', formData);
  } else {
    console.log('Form errors:', errors);
  }
};

				
			

Displaying Validation Errors

Store validation errors in the state and display them in the form.
				
					const [errors, setErrors] = useState({});

const handleSubmit = (e) => {
  e.preventDefault();
  const errors = validateForm();
  if (Object.keys(errors).length === 0) {
    console.log('Form submitted:', formData);
  } else {
    setErrors(errors);
  }
};

return (
  <form onSubmit={handleSubmit}>
    <div>
      <label htmlFor="name">Name:</label>
      <input
        type="text"
        id="name"
        name="name"
        value={formData.name}
        onChange={handleChange}
      />
      {errors.name && <p>{errors.name}</p>}
    </div>
    <div>
      <label htmlFor="email">Email:</label>
      <input
        type="email"
        id="email"
        name="email"
        value={formData.email}
        onChange={handleChange}
      />
      {errors.email && <p>{errors.email}</p>}
    </div>
    <button type="submit">Submit</button>
  </form>
);

				
			

Asynchronous Form Submission

For asynchronous form submissions (e.g., sending data to a server), use async/await and handle loading states.
				
					const handleSubmit = async (e) => {
  e.preventDefault();
  const errors = validateForm();
  if (Object.keys(errors).length === 0) {
    try {
      const response = await fetch('/api/submit', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      });
      const result = await response.json();
      console.log('Form submitted:', result);
    } catch (error) {
      console.error('Error submitting form:', error);
    }
  } else {
    setErrors(errors);
  }
};