0
0
ReactDebug / FixBeginner · 4 min read

How to Handle Form in React: Controlled Components Explained

In React, handle forms by using controlled components where form inputs are tied to state variables. Use onChange handlers to update state and onSubmit to process the form data.
🔍

Why This Happens

When you try to use a form input in React without connecting it to state, the input behaves unexpectedly or React shows warnings. This happens because React needs to control the input's value to keep the UI and data in sync.

jsx
import React from 'react';

function MyForm() {
  return (
    <form>
      <input type="text" />
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Output
Input field works but React warns: "Warning: A component is changing an uncontrolled input to be controlled."
🔧

The Fix

Make the input a controlled component by linking its value to React state and updating that state on every change. This keeps React in control and avoids warnings.

jsx
import React, { useState } from 'react';

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

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

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`Form submitted with name: ${name}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="name">Name:</label>
      <input
        id="name"
        type="text"
        value={name}
        onChange={handleChange}
        aria-label="Name input"
      />
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Output
A text input that updates as you type and shows an alert with the input value on submit.
🛡️

Prevention

Always use controlled components for form inputs in React. Initialize state for each input, update state on onChange, and handle form submission with onSubmit. Use semantic HTML and accessibility attributes like aria-label or label tags for better user experience.

Use React linting tools like eslint-plugin-react-hooks to catch common mistakes early.

⚠️

Related Errors

Common related errors include:

  • Uncontrolled to controlled input warning: Happens when input value changes from undefined to a string. Fix by initializing state properly.
  • Form not submitting: Usually caused by missing event.preventDefault() in submit handler.
  • Input not updating: Happens if value is set but onChange does not update state.

Key Takeaways

Use controlled components by linking input values to React state.
Update state on every input change with an onChange handler.
Prevent default form submission behavior to handle data in React.
Use semantic HTML and accessibility attributes for better UX.
Initialize state properly to avoid uncontrolled to controlled warnings.