SmartCodingTips

πŸ“ Controlled Forms in React

In React, a controlled form is a form where the form data is handled by the component’s state. This allows for easier validation, control, and logic based on user input.


πŸŽ›οΈ 1. Basic Controlled Input

Here's how to bind an input value to React state:


import { useState } from 'react';

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

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

  return (
    <div>
      <input type="text" value={name} onChange={handleChange} />
      <p>Hello, {name}</p>
    </div>
  );
}
  

βœ… 2. Why Use Controlled Inputs?

  • Better control over user input
  • Validation and formatting become easier
  • Works well with conditional logic

πŸ“¦ 3. Handle Multiple Inputs

You can manage multiple inputs by using one state object:


const [form, setForm] = useState({ name: '', email: '' });

function handleChange(e) {
  const { name, value } = e.target;
  setForm((prev) => ({ ...prev, [name]: value }));
}
  

πŸ“‹ 4. Submit the Form


function handleSubmit(e) {
  e.preventDefault();
  console.log(form);
}
  

Controlled components are the preferred method for managing form data in React, offering full control and predictability.