D Dev Notebook

React Form

A form in React is used to collect user input, like a name, email, or password.

React Forms are used to collect user input, just like in plain HTML. However, React gives you more control over form elements using state and event handlers. There are two main ways to work with forms in React:

1. Controlled Components

In controlled components, form inputs (like <input>, <textarea>, etc.) are controlled by React state.

Key Concepts:

  • The value of the form element is set by useState.
  • You update the state using onChange.
import { useState } from 'react';

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

  const handleSubmit = (e) => {
    e.preventDefault(); // prevents page reload
    alert(`Submitted name: ${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. Uncontrolled Components

In uncontrolled components, React does not control the form values. Instead, you use refs to access the DOM directly.

import { useRef } from 'react';

function ContactForm() {
  const nameInput = useRef();

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`Submitted name: ${nameInput.current.value}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name: 
        <input type="text" ref={nameInput} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

🆚 Controlled vs Uncontrolled

FeatureControlledUncontrolled
Data sourceReact stateDOM (via ref)
ValidationEasierHarder
IntegrationBetter with React appsMore like plain HTML

Code Snippets

On this page