Introduction to Forms
Forms are how users send information to a React app: logging in, searching, filling in an address, posting a comment. React does not replace the HTML form elements you already know. You still use <form>, <input>, <select> and <textarea>. What changes is how you read the values and what happens when the form is submitted, because a single-page app must not let the browser reload the page.
How a browser form behaves without React
By default, submitting a form makes the browser collect the field values, send them to the URL in the action attribute, and load whatever page the server returns. In a React app that full reload would wipe out your component state and defeat the point of a single-page app. So the first thing nearly every React form handler does is call event.preventDefault().
A first React form
The most common approach stores each field's value in state. The input shows the state value, and every keystroke updates the state through onChange. This is called a controlled input.
import { useState } from 'react';
function NewsletterForm() {
const [email, setEmail] = useState('');
const [message, setMessage] = useState('');
function handleSubmit(event) {
event.preventDefault();
if (!email.includes('@')) {
setMessage('Please enter a valid email address.');
return;
}
setMessage(`Thanks! We will write to ${email}.`);
setEmail('');
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
/>
<button type="submit">Subscribe</button>
{message && <p role="status">{message}</p>}
</form>
);
}
Why attach the handler to the form
Put the submit logic on the form's onSubmit, not on the button's onClick. The submit event fires when the user clicks the button and also when they press Enter inside a text field, so keyboard users get the same behaviour. It also lets built-in browser validation, such as required or type="email", run before your handler.
Submission is also a good moment to give feedback. Disable the submit button while a request is running so the user cannot send the same form twice, show a short status message when it finishes, and move keyboard focus to the first field with an error if validation fails. Small touches like these make a form feel reliable.
Options for reading values
| Approach | Good for |
|---|---|
| State per field (controlled) | Live validation, formatting as the user types, enabling the button only when valid |
Refs with useRef (uncontrolled) | Reading a value once on submit, file inputs |
new FormData(event.currentTarget) | Large forms where you only need values at submit time |
The coming lessons look at user input, submission and validation in more depth.
Slip-ups beginners make
Giving an input a value without an onChange makes it read-only, and React logs a warning about it. Either add a change handler or use defaultValue instead.
Any <button> inside a form defaults to type="submit". A "Show password" or "Add another item" button will therefore submit the form unexpectedly. Give such buttons type="button".
Finally, remember JSX names: htmlFor instead of for on labels, and className instead of class.
The essentials
Handle onSubmit on the form, call preventDefault(), keep values in state or read them on submit, and label every field so it is accessible.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.