SmartCodingTips

πŸ“ Handling Forms in React

Forms are essential for collecting user input. In React, form elements like inputs, checkboxes, and selects can be handled using state and event handlers to build dynamic and interactive forms.


βœ… Controlled Form Example

A controlled component is tied to the component’s state. Every change updates the state in real-time.


function MyForm() {
  const [name, setName] = React.useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    alert("Name 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>
  );
}

The value of the input is controlled by the React state variable name.

πŸ”˜ Handling Checkboxes, Radio Buttons, and Select

Each input type can be managed with state and onChange handlers.


function Preferences() {
  const [selectedOption, setSelectedOption] = React.useState("light");
  const [acceptTerms, setAcceptTerms] = React.useState(false);

  return (
    <form>
      <label>
        Theme:
        <select value={selectedOption} onChange={(e) => setSelectedOption(e.target.value)}>
          <option value="light">Light</option>
          <option value="dark">Dark</option>
        </select>
      </label>

      <label>
        <input 
          type="checkbox" 
          checked={acceptTerms} 
          onChange={(e) => setAcceptTerms(e.target.checked)} 
        />
        I accept the terms
      </label>
    </form>
  );
}

Form handling in React provides real-time data management and better control over form validation and submission.

πŸ“‹ Best Practices

  • Use controlled components for full control over input values
  • Group form state logically (e.g., using objects for related fields)
  • Prevent default form submissions with e.preventDefault()
  • Validate input on the fly or on submit