A form is any part of the interface where users enter, select, or submit data. Login pages, registration screens, profile editors, contact forms, search bars, newsletter subscriptions, and checkout pages are all forms.
React forms use familiar HTML elements such as input, textarea, select, and button, but React gives you a better way to connect those fields to component state and application logic. That makes it easier to validate data, show custom error messages, enable or disable buttons, display live previews, and submit information without reloading the page.
Forms are one of the most practical parts of React because real applications constantly ask users for information. If you understand form handling well, you can build a large part of day-to-day React interfaces.
In React, forms are usually handled in one of two ways: controlled components and uncontrolled components.
| Feature | Controlled Component | Uncontrolled Component |
|---|---|---|
| Where data lives | React state | The DOM itself |
| How value is read | From state | From a ref or the DOM element |
| Validation | Easy to run while the user types | Usually checked on submit |
| Recommended for | Most React forms | Simple cases and file inputs |
| Level of control | High | Lower |
A controlled component gets its current value from React state and updates that state through event handlers. This makes React the single source of truth for the field value.
An uncontrolled component keeps its current value in the DOM, and React reads it only when needed. That can be useful in a few cases, but controlled forms are usually the better default in React applications.
The simplest controlled form example is a text input connected to state. The input displays the state value, and the state updates every time the user types.
import { useState } from 'react'
function NameForm() {
const [name, setName] = useState('')
return (
<div>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter your name"
/>
<p>Hello, {name || 'Guest'}</p>
</div>
)
}
export default NameForm
This is the foundation of React form handling. Because the value is in state, you can use it anywhere else in the component.
When an HTML form is submitted, the browser usually refreshes the page. In React, we normally stop that default behavior by calling event.preventDefault(). This lets us validate the data, send it to an API, show a success message, or update the UI without leaving the page.
import { useState } from 'react'
function LoginForm() {
const [email, setEmail] = useState('')
const handleSubmit = (e) => {
e.preventDefault()
alert(`Submitted email: ${email}`)
}
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Email address"
/>
<button type="submit">Submit</button>
</form>
)
}
Real forms usually contain more than one field. A common React pattern is to store those related values inside one object and update the correct field by using the input's name attribute.
import { useState } from 'react'
function SignupForm() {
const [formData, setFormData] = useState({
firstName: '',
lastName: '',
email: ''
})
const handleChange = (e) => {
const { name, value } = e.target
setFormData((prev) => ({
...prev,
[name]: value
}))
}
const handleSubmit = (e) => {
e.preventDefault()
console.log(formData)
}
return (
<form onSubmit={handleSubmit}>
<input name="firstName" value={formData.firstName} onChange={handleChange} placeholder="First name" />
<input name="lastName" value={formData.lastName} onChange={handleChange} placeholder="Last name" />
<input name="email" type="email" value={formData.email} onChange={handleChange} placeholder="Email" />
<button type="submit">Create Account</button>
</form>
)
}
This approach scales well and keeps related values together in one piece of state.
Most form elements use the same overall pattern, but there are a few important differences to remember.
Text, email, password, and number inputs usually use value and onChange.
In React, a textarea is usually controlled through the value prop rather than text between opening and closing tags.
In React, the selected option is normally controlled by the value prop on the select element.
Checkboxes use checked and e.target.checked instead of the normal text input pattern.
Radio buttons usually share the same name, and the selected value is based on a comparison such as checked={form.role === 'admin'}.
import { useState } from 'react'
function ProfileForm() {
const [form, setForm] = useState({
fullName: '',
bio: '',
country: 'india',
gender: 'female',
subscribe: false
})
const handleChange = (e) => {
const { name, value, type, checked } = e.target
setForm((prev) => ({
...prev,
[name]: type === 'checkbox' ? checked : value
}))
}
return (
<form>
<input type="text" name="fullName" value={form.fullName} onChange={handleChange} placeholder="Full name" />
<textarea name="bio" value={form.bio} onChange={handleChange} rows={4} placeholder="Write a short bio" />
<select name="country" value={form.country} onChange={handleChange}>
<option value="india">India</option>
<option value="usa">United States</option>
<option value="uk">United Kingdom</option>
</select>
<label>
<input type="radio" name="gender" value="female" checked={form.gender === 'female'} onChange={handleChange} />
Female
</label>
<label>
<input type="radio" name="gender" value="male" checked={form.gender === 'male'} onChange={handleChange} />
Male
</label>
<label>
<input type="checkbox" name="subscribe" checked={form.subscribe} onChange={handleChange} />
Subscribe to updates
</label>
</form>
)
}
const handleChange = (e) => {
const { name, value, type, checked } = e.target
setForm((prev) => ({
...prev,
[name]: type === 'checkbox' ? checked : value
}))
}
The generic change handler is especially useful because it works for text fields, textarea, select, radio buttons, and checkboxes with only one function.
Since controlled values are always in state, you can instantly display a preview, compute derived values, or react to user input in real time.
import { useState } from 'react'
function MessageForm() {
const [message, setMessage] = useState('')
return (
<div>
<textarea
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Type your message"
/>
<h4>Preview</h4>
<p>{message || 'Your preview will appear here.'}</p>
</div>
)
}
Validation means checking that the entered data is acceptable before the form is submitted. For example, you may want to require a name, verify an email format, check password length, or ensure the user agrees to the terms.
Validation can happen in several ways:
onBlurimport { useState } from 'react'
function ValidationForm() {
const [form, setForm] = useState({ email: '', password: '' })
const [errors, setErrors] = useState({})
const [touched, setTouched] = useState({})
const validate = (values) => {
const newErrors = {}
if (!values.email.trim()) newErrors.email = 'Email is required'
else if (!/\S+@\S+\.\S+/.test(values.email)) newErrors.email = 'Enter a valid email address'
if (!values.password.trim()) newErrors.password = 'Password is required'
else if (values.password.length < 8) newErrors.password = 'Password must be at least 8 characters'
return newErrors
}
const handleChange = (e) => {
const { name, value } = e.target
const nextForm = { ...form, [name]: value }
setForm(nextForm)
if (touched[name]) {
setErrors(validate(nextForm))
}
}
const handleBlur = (e) => {
const { name } = e.target
setTouched((prev) => ({ ...prev, [name]: true }))
setErrors(validate(form))
}
const handleSubmit = (e) => {
e.preventDefault()
const allTouched = { email: true, password: true }
const validationErrors = validate(form)
setTouched(allTouched)
setErrors(validationErrors)
if (Object.keys(validationErrors).length === 0) {
alert('Form submitted successfully')
}
}
return (
<form onSubmit={handleSubmit}>
<div>
<input type="email" name="email" value={form.email} onChange={handleChange} onBlur={handleBlur} placeholder="Email" />
{touched.email && errors.email && <p>{errors.email}</p>}
</div>
<div>
<input type="password" name="password" value={form.password} onChange={handleChange} onBlur={handleBlur} placeholder="Password" />
{touched.password && errors.password && <p>{errors.password}</p>}
</div>
<button type="submit">Login</button>
</form>
)
}
const validate = (values) => {
const newErrors = {}
if (!values.email.trim()) newErrors.email = 'Email is required'
else if (!/\S+@\S+\.\S+/.test(values.email)) newErrors.email = 'Enter a valid email address'
if (!values.password.trim()) newErrors.password = 'Password is required'
else if (values.password.length < 8) newErrors.password = 'Password must be at least 8 characters'
return newErrors
}
This pattern uses two extra pieces of state:
errors stores validation messagestouched tracks which fields the user has interacted withThat helps avoid showing every error immediately when the page first loads.
Some forms disable the submit button until the entered data looks valid. This improves clarity and reduces unnecessary requests.
import { useState } from 'react'
function NewsletterForm() {
const [email, setEmail] = useState('')
const isValid = /\S+@\S+\.\S+/.test(email)
const handleSubmit = (e) => {
e.preventDefault()
alert('Subscribed successfully')
}
return (
<form onSubmit={handleSubmit}>
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Enter your email" />
<button type="submit" disabled={!isValid}>Subscribe</button>
</form>
)
}
After a successful submission, it is common to clear the fields. Controlled forms make this easy because you only need to reset the state back to its initial values.
import { useState } from 'react'
const initialForm = {
name: '',
message: ''
}
function ContactForm() {
const [form, setForm] = useState(initialForm)
const handleChange = (e) => {
const { name, value } = e.target
setForm((prev) => ({ ...prev, [name]: value }))
}
const handleSubmit = (e) => {
e.preventDefault()
console.log('Sending form data:', form)
setForm(initialForm)
}
return (
<form onSubmit={handleSubmit}>
<input name="name" value={form.name} onChange={handleChange} placeholder="Your name" />
<textarea name="message" value={form.message} onChange={handleChange} placeholder="Your message" />
<button type="submit">Send</button>
</form>
)
}
React also allows uncontrolled fields. In that approach, you do not keep the current value in state. Instead, you read the value from the DOM using a ref.
import { useRef } from 'react'
function SearchForm() {
const searchRef = useRef(null)
const handleSubmit = (e) => {
e.preventDefault()
alert(`Searching for: ${searchRef.current.value}`)
}
return (
<form onSubmit={handleSubmit}>
<input ref={searchRef} type="text" placeholder="Search..." />
<button type="submit">Search</button>
</form>
)
}
Uncontrolled fields can work, but they give React less direct control over the current value. That is why controlled components are usually preferred for complex forms.
File inputs are a special case. Browsers do not allow JavaScript to fully control the current file value for security reasons, so file inputs are typically handled as uncontrolled elements.
function ResumeUpload() {
const handleChange = (e) => {
const file = e.target.files[0]
if (file) {
console.log('Selected file:', file.name)
}
}
return (
<div>
<label>Upload resume</label>
<input type="file" onChange={handleChange} />
</div>
)
}
The next example combines several important concepts: multiple fields, one shared change handler, validation, checkbox handling, select handling, submit logic, and form reset behavior. This is much closer to what you would build in a real application.
import { useState } from 'react'
const initialValues = {
name: '',
email: '',
password: '',
role: 'student',
agree: false,
about: ''
}
function RegistrationForm() {
const [form, setForm] = useState(initialValues)
const [errors, setErrors] = useState({})
const [submitted, setSubmitted] = useState(false)
const validate = (values) => {
const nextErrors = {}
if (!values.name.trim()) nextErrors.name = 'Name is required'
if (!values.email.trim()) nextErrors.email = 'Email is required'
else if (!/\S+@\S+\.\S+/.test(values.email)) nextErrors.email = 'Enter a valid email address'
if (!values.password.trim()) nextErrors.password = 'Password is required'
else if (values.password.length < 8) nextErrors.password = 'Password must be at least 8 characters'
if (!values.agree) nextErrors.agree = 'You must accept the terms'
return nextErrors
}
const handleChange = (e) => {
const { name, value, type, checked } = e.target
setForm((prev) => ({
...prev,
[name]: type === 'checkbox' ? checked : value
}))
}
const handleSubmit = (e) => {
e.preventDefault()
const validationErrors = validate(form)
setErrors(validationErrors)
if (Object.keys(validationErrors).length === 0) {
console.log('Submitted data:', form)
setSubmitted(true)
setForm(initialValues)
} else {
setSubmitted(false)
}
}
return (
<form onSubmit={handleSubmit}>
<input type="text" name="name" value={form.name} onChange={handleChange} placeholder="Full name" />
{errors.name && <p>{errors.name}</p>}
<input type="email" name="email" value={form.email} onChange={handleChange} placeholder="Email" />
{errors.email && <p>{errors.email}</p>}
<input type="password" name="password" value={form.password} onChange={handleChange} placeholder="Password" />
{errors.password && <p>{errors.password}</p>}
<select name="role" value={form.role} onChange={handleChange}>
<option value="student">Student</option>
<option value="developer">Developer</option>
<option value="designer">Designer</option>
</select>
<textarea name="about" value={form.about} onChange={handleChange} placeholder="Tell us about yourself" rows={4} />
<label>
<input type="checkbox" name="agree" checked={form.agree} onChange={handleChange} />
I agree to the terms and conditions
</label>
{errors.agree && <p>{errors.agree}</p>}
<button type="submit">Register</button>
{submitted && <p>Registration completed successfully.</p>}
</form>
)
}
const validate = (values) => {
const nextErrors = {}
if (!values.name.trim()) nextErrors.name = 'Name is required'
if (!values.email.trim()) nextErrors.email = 'Email is required'
else if (!/\S+@\S+\.\S+/.test(values.email)) nextErrors.email = 'Enter a valid email address'
if (!values.password.trim()) nextErrors.password = 'Password is required'
else if (values.password.length < 8) nextErrors.password = 'Password must be at least 8 characters'
if (!values.agree) nextErrors.agree = 'You must accept the terms'
return nextErrors
}
For small and medium forms, useState is usually enough. But when a form becomes large, has many update rules, or contains multiple sections, useReducer can keep the logic easier to understand. Instead of spreading update logic throughout the component, you can dispatch actions such as update_field, set_errors, and reset_form.
name attribute to build reusable change handlerschecked for checkboxes instead of valuepreventDefault() in React submit handlersuseReducer when form logic becomes too complexvaluevalue instead of checked for a checkboxpreventDefault() on submitReact forms are based on normal HTML form elements, but React makes them more powerful by connecting field values to state and event handlers. Controlled components are the main pattern because they make validation, conditional UI, previews, submission, and reset logic much easier to manage.
Once you understand controlled inputs, shared change handlers, validation, submit handling, reset patterns, and the role of refs for uncontrolled fields, you can build most real-world React forms confidently.
Explore 500+ free tutorials across 20+ languages and frameworks.