form handling

Form Handling in React

  • Profile picture of Mcs
  • by Mcs July 3, 2025

In React, form handling means capturing user input from form fields like <input>, <textarea>, <select>, etc., and managing the data using state.

1. Controlled Components

React forms are usually controlled components, meaning form values are controlled by React state.

Basic Input Form Example

import { useState } from 'react';

function SimpleForm() {
 const [name, setName] = useState('');

 const handleSubmit = (e) => {
   e.preventDefault(); // prevent page reload
   alert(`Submitted: ${name}`);
 };

 return (
   <form onSubmit={handleSubmit}>
     <label>
       Name: 
       <input 
         type="text"
         value={name}
         onChange={(e) => setName(e.target.value)}
       />
     </label>
     <button type="submit">Submit</button>
   </form>
 );
}

2. Multiple Fields Handling

function MultiForm() {
 const [formData, setFormData] = useState({
   username: '',
   email: '',
 });

 const handleChange = (e) => {
   const { name, value } = e.target;

   setFormData((prev) => ({
     ...prev,
     [name]: value,
   }));
 };

 const handleSubmit = (e) => {
   e.preventDefault();
   console.log(formData);
 };

 return (
   <form onSubmit={handleSubmit}>
     <input
       name="username"
       placeholder="Username"
       value={formData.username}
       onChange={handleChange}
     />
     <input
       name="email"
       placeholder="Email"
       value={formData.email}
       onChange={handleChange}
     />
     <button type="submit">Submit</button>
   </form>
 );
}

3. Select Dropdown, Checkbox, Radio Example

function AdvancedForm() {
 const [gender, setGender] = useState('male');
 const [terms, setTerms] = useState(false);

 const handleSubmit = (e) => {
   e.preventDefault();
   alert(`Gender: ${gender}, Accepted Terms: ${terms}`);
 };

 return (
   <form onSubmit={handleSubmit}>
     <label>
       Gender:
       <select value={gender} onChange={(e) => setGender(e.target.value)}>
         <option value="male">Male</option>
         <option value="female">Female</option>
       </select>
     </label>

     <label>
       <input
         type="checkbox"
         checked={terms}
         onChange={(e) => setTerms(e.target.checked)}
       />
       Accept Terms
     </label>

     <button type="submit">Submit</button>
   </form>
 );
}

Summary: Form Handling in React

ConceptDescription
Controlled InputsInput value is controlled by React useState()
onChangeUpdates state as user types or selects
onSubmitCalled when form is submitted
Multiple fieldsUse an object with field names as keys

Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <br> <p> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <cite> <dl> <dt> <dd> <a hreflang href> <blockquote cite> <ul type> <ol type start> <strong> <em> <code> <li>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.