Skip to content

React Forms: Inputs, Submit and Validation

Most React forms keep each field’s value in state. The input shows that state (value={name}) and updates it on every key (onChange). That’s a controlled input. To send the form, put onSubmit on the <form> and call e.preventDefault() so the page doesn’t reload. For simple forms you can skip the state and read the values with FormData when it’s sent, and React 19 adds form actions for that.

One input, one piece of state

Here’s the smallest useful example. Type a name and the greeting follows along:

NameField.jsx
import { useState } from 'react';export default function NameField() {  const [name, setName] = useState('Sam');  return (    <div>      <label>        Your name <input value={name} onChange={(e) => setName(e.target.value)} />      </label>      <p>Hello, {name || 'stranger'}!</p>    </div>  );}
Open in React Playground
HTML from NameField

Typing in the white box won’t change its greeting. That’s only the HTML React wrote the first time, with nothing running behind it. To type into the real thing, open the playground link and press Run.

Controlled inputs

In plain HTML, the input keeps its own text and you read it when you need it. In NameField, React owns the text instead: value={name} says “show what’s in state”, and onChange={(e) => setName(e.target.value)} copies each key press back into state. React’s onChange fires on every key, not when the box loses focus like the HTML change event.

Why go to that trouble? Because the value is now a normal variable. You can show it somewhere else, check it as people type, clear the box with setName(''), or turn it into uppercase on the way in. Leave out the onChange, though, and nobody can type at all:

value vs defaultValue
// Nobody can type in this onefunction Locked() {  return <input value="Sam" />;}// A starting value people can changefunction Editable() {  return <input defaultValue="Sam" />;}

React warns about the first one in the console: “You provided a value prop to a form field without an onChange handler. This will render a read-only field.” defaultValue sets the starting text and then lets the input manage itself (that’s an uncontrolled input, more on those below).

Many inputs, one handler

A separate useState for every field gets long. Keep the whole form in one object, give each input a name that matches a key, and let one function handle them all:

OrderForm.jsx
import { useState } from 'react';export default function OrderForm() {  const [form, setForm] = useState({ name: '', email: '', drink: 'Latte' });  function handleChange(e) {    const { name, value } = e.target;    setForm({ ...form, [name]: value });  }  return (    <form>      <label>        Name <input name="name" value={form.name} onChange={handleChange} />      </label>      <label>        Email <input name="email" type="email" value={form.email} onChange={handleChange} />      </label>      <label>        Drink <input name="drink" value={form.drink} onChange={handleChange} />      </label>      <p>        {form.name || 'Someone'} wants a {form.drink || 'mystery drink'}.      </p>    </form>  );}
Open in React Playground

[name]: value uses the input’s name as the key, so typing in the Email box updates form.email, and ...form keeps the other fields as they were. Add a field later and you only add an input with a new name and a starting value.

Checkboxes

A checkbox is on or off, so it uses checked instead of value, and you read e.target.checked (true or false). A group of checkboxes fits nicely into an array:

Extras.jsx
import { useState } from 'react';const ALL_TOPPINGS = ['Cinnamon', 'Cocoa', 'Vanilla syrup'];export default function Extras() {  const [oatMilk, setOatMilk] = useState(false);  const [toppings, setToppings] = useState(['Cinnamon']);  function toggle(topping) {    setToppings(      toppings.includes(topping) ? toppings.filter((t) => t !== topping) : [...toppings, topping]    );  }  return (    <div>      <label>        <input type="checkbox" checked={oatMilk} onChange={(e) => setOatMilk(e.target.checked)} /> Oat milk      </label>      <fieldset>        <legend>Toppings</legend>        {ALL_TOPPINGS.map((t) => (          <label key={t}>            <input type="checkbox" checked={toppings.includes(t)} onChange={() => toggle(t)} /> {t}          </label>        ))}      </fieldset>      <p>        {oatMilk ? 'Oat milk' : 'Regular milk'}, with {toppings.length ? toppings.join(', ') : 'no toppings'}.      </p>    </div>  );}
Open in React Playground
HTML from Extras

checked={toppings.includes(t)} ticks the boxes that are in the array, and toggle adds or removes one. In the live box, React wrote checked="" on Cinnamon only. Reading e.target.value from a checkbox is a common slip: it gives the box’s value attribute (“on” when there isn’t one), whether it’s ticked or not.

Radio buttons

Radio buttons share one piece of state. Each button is checked when the state matches its value:

CupSize.jsx
import { useState } from 'react';const SIZES = ['small', 'medium', 'large'];export default function CupSize() {  const [size, setSize] = useState('medium');  return (    <fieldset>      <legend>Cup size</legend>      {SIZES.map((s) => (        <label key={s}>          <input            type="radio"            name="size"            value={s}            checked={size === s}            onChange={(e) => setSize(e.target.value)}          />{' '}          {s}        </label>      ))}      <p>You picked a {size} cup.</p>    </fieldset>  );}
Open in React Playground

Give all the buttons in a group the same name. React doesn’t need it, but the browser does: it’s what makes the arrow keys move between them, and only one of them gets sent if the form is ever submitted the normal way. The <fieldset> and <legend> give the group a label that screen readers announce.

Select (dropdown)

In HTML you mark the chosen option with selected. In React you put value on the <select> itself, which is much easier to keep in state:

DrinkPicker.jsx
import { useState } from 'react';export default function DrinkPicker() {  const [drink, setDrink] = useState('flat-white');  return (    <div>      <label>        Drink{' '}        <select value={drink} onChange={(e) => setDrink(e.target.value)}>          <option value="latte">Latte</option>          <option value="flat-white">Flat white</option>          <option value="mocha">Mocha</option>        </select>      </label>      <p>Value sent: {drink}</p>    </div>  );}
Open in React Playground
HTML from DrinkPicker

React still writes selected on the matching option in the HTML, as the live box shows. If you write selected on an option yourself, React warns: “Use the defaultValue or value props on <select> instead of setting selected on <option>.” For a list where people can pick several, add multiple and keep an array:

Pastries.jsx
import { useState } from 'react';export default function Pastries() {  const [picked, setPicked] = useState(['croissant']);  function handleChange(e) {    setPicked(Array.from(e.target.selectedOptions, (option) => option.value));  }  return (    <div>      <label>        Pastries (hold Ctrl or Cmd to pick more)        <select multiple value={picked} onChange={handleChange}>          <option value="croissant">Croissant</option>          <option value="muffin">Blueberry muffin</option>          <option value="scone">Scone</option>        </select>      </label>      <p>{picked.length} picked: {picked.join(', ') || 'none'}</p>    </div>  );}
Open in React Playground

e.target.selectedOptions is the browser’s list of picked options, and Array.from turns it into an array of their values. Multiple selects are awkward on a computer (Ctrl-click), so for three or four choices, checkboxes are often friendlier.

Textarea

In HTML a textarea’s text goes between the tags. In React it’s a value, exactly like an input:

Review.jsx
import { useState } from 'react';const MAX = 120;export default function Review() {  const [text, setText] = useState('');  return (    <label>      How was your coffee?      <textarea value={text} onChange={(e) => setText(e.target.value)} maxLength={MAX} rows={3} />      <small>{MAX - text.length} characters left</small>    </label>  );}
Open in React Playground

Text between <textarea> and </textarea> gets a console warning (“Use the defaultValue or value props instead of setting children on <textarea>”). Because the text is in state, the counter under it is one line of math. maxLength stops typing at 120.

Submitting the form

Put your code in onSubmit on the form, rather than onClick on the button:

Newsletter.jsx
import { useState } from 'react';export default function Newsletter() {  const [email, setEmail] = useState('');  const [sent, setSent] = useState(false);  function handleSubmit(e) {    e.preventDefault(); // stop the browser from reloading the page    setSent(true); // this is where you would send it to your server  }  if (sent) return <p>Thanks! The menu is on its way to {email}.</p>;  return (    <form onSubmit={handleSubmit}>      <label>        Email <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />      </label>      <button type="submit">Send me the menu</button>    </form>  );}
Open in React Playground

A form’s normal job is to send the data to a URL and load a new page. e.preventDefault() stops that, so your code decides what happens: here it shows a thank-you, in a real app it would send the email to your server with fetch. Notice the required and type="email". The browser checks those first and only fires onSubmit when they pass, so an empty box or “sam@” never gets as far as your function.

That’s the main reason to prefer onSubmit over the button’s onClick. Pressing Enter in a field clicks the submit button for you, so an onClick runs either way, but it runs before the browser’s checks. Call e.preventDefault() there and the form is never checked at all; leave it out and the form goes on to send itself and reload the page. onSubmit fires however the form is sent (a click, Enter, or code calling form.requestSubmit()), and only once the checks pass. Inside a form, a <button> submits it unless you write type="button".

Validation and error messages

The browser’s own checks are a good start, but their messages look different in every browser and you can’t style them. For your own messages, check the values in onSubmit and keep the problems in state:

PreOrder.jsx
import { useState } from 'react';function validate(values) {  const errors = {};  if (!values.name.trim()) errors.name = 'Please tell us your name.';  if (!/^\S+@\S+\.\S+$/.test(values.email)) errors.email = 'That email looks incomplete.';  const cups = Number(values.cups);  if (!Number.isInteger(cups) || cups < 1 || cups > 10) errors.cups = 'Pick between 1 and 10 cups.';  return errors;}function Field({ label, name, error, ...inputProps }) {  return (    <div className="field">      <label htmlFor={name}>{label}</label>      <input        id={name}        name={name}        aria-invalid={error ? true : undefined}        aria-describedby={error ? name + '-error' : undefined}        {...inputProps}      />      {error && <p id={name + '-error'} className="error">{error}</p>}    </div>  );}export default function PreOrder() {  const [values, setValues] = useState({ name: '', email: '', cups: '1' });  const [errors, setErrors] = useState({});  const [done, setDone] = useState(false);  function handleChange(e) {    const { name, value } = e.target;    setValues({ ...values, [name]: value });    if (errors[name]) setErrors({ ...errors, [name]: undefined }); // clear it as they fix it  }  function handleSubmit(e) {    e.preventDefault();    const found = validate(values);    setErrors(found);    if (Object.keys(found).length === 0) setDone(true);  }  if (done) return <p>Got it, {values.name}: {values.cups} cups for pickup.</p>;  return (    <form onSubmit={handleSubmit} noValidate>      <Field label="Name" name="name" value={values.name} onChange={handleChange} error={errors.name} />      <Field label="Email" name="email" type="email" value={values.email} onChange={handleChange} error={errors.email} />      <Field label="Cups" name="cups" type="number" value={values.cups} onChange={handleChange} error={errors.cups} />      <button type="submit">Pre-order</button>    </form>  );}
Open in React Playground

Press Pre-order straight away and two messages appear, under Name and Email. Put 12 in Cups and press it again, and Cups gets a message too. A few things make this one pleasant to use. noValidate on the form switches off the browser’s pop-ups, so people only see your messages. Each error disappears as soon as someone edits that field. And aria-invalid plus aria-describedby tell screen readers which field is wrong and read the message out with it.

One detail catches everybody once: e.target.value is always text, even for type="number". That’s why validate runs Number(values.cups) before comparing. And checks in the browser are only for the person’s convenience. Your server still has to check everything again, because anyone can send it whatever they like.

Uncontrolled inputs: FormData and useRef

You don’t have to keep every field in state. If you only need the values when the form is sent, let the inputs manage themselves and read them all at once with FormData:

Feedback.jsx
import { useState } from 'react';export default function Feedback() {  const [summary, setSummary] = useState('');  function handleSubmit(e) {    e.preventDefault();    const data = new FormData(e.currentTarget);    const name = data.get('name');    const stars = data.get('stars');    const again = data.get('again') === 'on'; // a ticked checkbox sends "on"    setSummary(`${name} gave ${stars} stars${again ? ' and will come back' : ''}.`);  }  return (    <form onSubmit={handleSubmit}>      <label>        Name <input name="name" defaultValue="Sam" />      </label>      <label>        Stars{' '}        <select name="stars" defaultValue="5">          <option>3</option>          <option>4</option>          <option>5</option>        </select>      </label>      <label>        <input type="checkbox" name="again" defaultChecked /> I’d come back      </label>      <button type="submit">Send feedback</button>      {summary && <p>{summary}</p>}    </form>  );}
Open in React Playground

new FormData(e.currentTarget) collects every field that has a name, the same way a browser would send them. defaultValue and defaultChecked set where each field starts. Watch out for checkboxes: a ticked one sends "on" (or its value), and an unticked one isn’t in the data at all, so data.get('again') is null. For a group with the same name, data.getAll('topping') gives you an array.

For a single field, a ref is enough. This one reads the box, then clears it and puts the cursor back:

QuickNote.jsx
import { useRef } from 'react';export default function QuickNote() {  const noteRef = useRef(null);  function save() {    console.log('Note:', noteRef.current.value);    noteRef.current.value = '';    noteRef.current.focus();  }  return (    <div>      <input ref={noteRef} defaultValue="Extra hot, please" aria-label="Note for the barista" />      <button onClick={save}>Save note</button>    </div>  );}
Open in React Playground

Use controlled inputs when the page reacts while people type (live previews, counters, a button that only lights up when the form is complete). Use uncontrolled ones when you only care about the values at the end. Both are normal React, and one form can mix them.

React 19 form actions

React 19 lets you pass a function to the form’s action. React calls it with the form’s FormData when the form is sent, so there’s no onSubmit and no preventDefault:

GuestBook.jsx
import { useState } from 'react';export default function GuestBook() {  const [names, setNames] = useState([]);  function addName(formData) {    const name = formData.get('name').trim();    if (name) setNames((list) => [...list, name]);  }  return (    <form action={addName}>      <label>        Your name <input name="name" placeholder="Sam" />      </label>      <button type="submit">Sign the guest book</button>      <ul>        {names.map((n, i) => (          <li key={i}>{n}</li>        ))}      </ul>    </form>  );}
Open in React Playground

Sign the guest book and look at the box: it’s empty again. When the action has finished, React resets the form’s uncontrolled fields for you. That’s what you want here, and a surprise if you didn’t expect it. Controlled inputs keep whatever their state says.

Actions can be async, and useActionState gives you what the last run returned plus a pending flag, which is most of what a sign-up form needs:

JoinList.jsx
import { useActionState } from 'react';// Pretends to be a server that takes a moment.function saveEmail(email) {  return new Promise((resolve) => setTimeout(resolve, 800));}async function joinList(previousState, formData) {  const email = formData.get('email').trim();  if (!email.includes('@')) {    return { error: 'That email needs an @ in it.', email };  }  await saveEmail(email);  return { message: `Thanks! ${email} is on the list.` };}export default function JoinList() {  const [state, formAction, isPending] = useActionState(joinList, {});  return (    <form action={formAction}>      <label>        Email <input name="email" defaultValue={state.email} />      </label>      <button type="submit" disabled={isPending}>        {isPending ? 'Saving...' : 'Join the list'}      </button>      {state.error && <p className="error">{state.error}</p>}      {state.message && <p>{state.message}</p>}    </form>  );}
Open in React Playground

useActionState(joinList, {}) returns three things: state (whatever joinList returned last time, starting as {}), formAction to put on the form, and isPending, true while the action runs. Note the order of the action’s arguments: the previous state first, then the form data. Try an email without an @: the error shows, and because the reset puts each field back to its defaultValue, defaultValue={state.email} brings back what was typed so it can be fixed.

A couple of related pieces. useFormStatus from react-dom lets a submit button component inside the form read pending without props. And in frameworks such as Next.js, an action can be a server function (marked 'use server') that runs on the server. In a plain React app like these examples, it runs in the browser.

Common mistakes and warnings

  • “A component is changing an uncontrolled input to be controlled.” The state started as undefined (useState() with nothing in it), so the input began uncontrolled and became controlled once you typed. Start text fields with useState('').
  • “value prop on input should not be null.” Data from a server often has null for empty fields. Use value={phone ?? ''}.
  • Numbers that join instead of add. The value of a number input is text, so cups + 1 with cups at "2" shows 21:
Cups.jsx (shows 21 when you type 2)
import { useState } from 'react';export default function Cups() {  const [cups, setCups] = useState(1);  return (    <div>      <label>        Cups <input type="number" value={cups} onChange={(e) => setCups(e.target.value)} />      </label>      <p>Plus one for Sam: {cups + 1}</p>    </div>  );}
Open in React Playground
  • Fix: convert it when you use it, Number(cups) + 1, or keep the text in state and convert in one place, like the validation example does.
  • The page reloads on submit. e.preventDefault() is missing from onSubmit, or the code sits in the button’s onClick, where nothing stops the form from sending. With a function in action React handles this for you.
  • A button that submits by surprise. Any <button> inside a form is a submit button. Give the extra ones (Clear, Show password) type="button".
  • Labels that don’t work. In JSX it’s htmlFor, not for: <label htmlFor="email">. Or wrap the input inside the label, like most examples here. See what is JSX for the other renamed attributes.

Questions people ask

What is a controlled input in React?

An input whose value comes from React state: value={name} shows the state and onChange={(e) => setName(e.target.value)} updates it on every key. React owns the text, so you can show it elsewhere, check it while people type, or clear it with setName('').

What is the difference between controlled and uncontrolled inputs?

A controlled input gets its value from state and needs an onChange. An uncontrolled input keeps its own text, like plain HTML: you set where it starts with defaultValue (or defaultChecked) and read it when needed, with a ref or with new FormData(form) on submit. Use controlled when the page reacts while people type, uncontrolled when you only need the values at the end.

How do I handle form submit in React?

Put onSubmit on the <form> and start it with e.preventDefault() so the browser doesn’t reload the page, then use the values or send them with fetch. onSubmit runs only after the browser’s own checks (required, type="email") pass, and it fires however people send the form (a click or Enter). An onClick on the button runs before those checks, so it either skips them or lets the page reload. In React 19 you can instead pass a function to <form action={fn}>, which gets the FormData and needs no preventDefault.

How do I handle many inputs with one onChange handler?

Keep the form in one state object, give every input a name that matches a key, and use one handler: const { name, value } = e.target; setForm({ ...form, [name]: value }). For checkboxes read e.target.checked instead of e.target.value.

Why can’t I type in my React input?

It has a value but no onChange, so React keeps putting the same value back. React warns about it in the console. Add an onChange that updates the state, or use defaultValue if you only want a starting value.

How do I validate a form in React?

Check the values in your submit handler, keep the problems in an errors object in state, and show each message under its field. Add noValidate to the form if you want only your messages, and aria-invalid plus aria-describedby so screen readers connect each message to its field. Your server still has to check the data again.

How do checkboxes, radio buttons and selects work in React?

Checkboxes use checked={value} and e.target.checked. Radio buttons share one piece of state, each with checked={size === "small"} and the same name. A select takes value on the <select> itself, not selected on an option, and multiple selects take an array.

What is useActionState in React 19?

A hook for forms that use actions. const [state, formAction, isPending] = useActionState(fn, initialState) gives you what the action returned last time, a formAction to pass to <form action>, and a flag that is true while it runs. The action is called with the previous state first and the FormData second.

Why does my React form reset after submitting?

In React 19, when a form uses a function in its action prop, React resets the form’s uncontrolled fields after the action finishes. Controlled inputs keep their state. To keep what was typed (for example after an error), return it from the action and use it as the field’s defaultValue.

Tools that help