CPCODELAB
React

Forms and Controlled Inputs

10 min read

Making React Own Form State

In a controlled input, React state is the single source of truth. The value prop is tied to state, and onChange updates state on every keystroke. This gives you full control over validation, formatting, and submission.

jsx
import { useState } from 'react';

function SignupForm() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");

  function handleSubmit(e) {
    e.preventDefault();
    console.log({ name, email });
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={name}
        onChange={e => setName(e.target.value)}
        placeholder="Name"
      />
      <input
        type="email"
        value={email}
        onChange={e => setEmail(e.target.value)}
        placeholder="Email"
      />
      <button type="submit">Sign Up</button>
    </form>
  );
}

For complex forms with many fields, consider a single formData object in state and a generic handleChange that uses e.target.name to update the right key.

Ready to test yourself?
Practice React— quiz & coding exercises