Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

React Forms Controlled Components, Validation: Tutorial, Examples, FAQs & Interview Tips

What are Forms in React?

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.

Why Form Handling Matters

  • Forms collect data from users
  • Forms often need validation before submission
  • Forms usually contain multiple related fields
  • Forms react to typing, focusing, blurring, selecting, checking, and submitting
  • Good form logic improves both user experience and code maintainability

Controlled and Uncontrolled Forms

In React, forms are usually handled in one of two ways: controlled components and uncontrolled components.

FeatureControlled ComponentUncontrolled Component
Where data livesReact stateThe DOM itself
How value is readFrom stateFrom a ref or the DOM element
ValidationEasy to run while the user typesUsually checked on submit
Recommended forMost React formsSimple cases and file inputs
Level of controlHighLower

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.

Basic Controlled Input

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.

Controlled Text Input
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.

Handling Form Submission

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.

Submit a Simple Form
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>
    )
}

Working with Multiple Fields

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.

One State Object for Many Inputs
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.

React Form Elements and Their Differences

Most form elements use the same overall pattern, but there are a few important differences to remember.

Text Input

Text, email, password, and number inputs usually use value and onChange.

Textarea

In React, a textarea is usually controlled through the value prop rather than text between opening and closing tags.

Select

In React, the selected option is normally controlled by the value prop on the select element.

Checkbox

Checkboxes use checked and e.target.checked instead of the normal text input pattern.

Radio Buttons

Radio buttons usually share the same name, and the selected value is based on a comparison such as checked={form.role === 'admin'}.

All Common Input Types
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.

Showing Live Form Data

Since controlled values are always in state, you can instantly display a preview, compute derived values, or react to user input in real time.

Live Preview Example
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>
    )
}

Validating Forms in React

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:

  • While the user types
  • When the field loses focus using onBlur
  • When the user submits the form
  • With a combination of blur and submit for a better experience
Validation with Errors and Touched Fields
import { 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 messages
  • touched tracks which fields the user has interacted with

That helps avoid showing every error immediately when the page first loads.

Disabling the Submit Button

Some forms disable the submit button until the entered data looks valid. This improves clarity and reduces unnecessary requests.

Disable Submit Until Form Is Ready
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>
    )
}

Resetting a 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.

Reset Form 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>
    )
}

Uncontrolled Components with useRef

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.

Uncontrolled Form Example
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 in React

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.

File Input Example
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>
    )
}

A Complete Practical Example

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.

Complete Registration Form
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
}

When useReducer Can Help with Forms

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.

Best Practices for React Forms

  • Use controlled components for most form fields
  • Keep the form state shape simple and predictable
  • Use the name attribute to build reusable change handlers
  • Use checked for checkboxes instead of value
  • Call preventDefault() in React submit handlers
  • Show clear validation messages near the related field
  • Reset the form after a successful submission when appropriate
  • Use refs for file inputs and other uncontrolled cases
  • Consider useReducer when form logic becomes too complex

Common Mistakes

  • Forgetting to give a controlled input a value
  • Mutating the old form object directly instead of creating a new one
  • Using value instead of checked for a checkbox
  • Forgetting to call preventDefault() on submit
  • Showing every validation error before the user has touched the field
  • Writing too many separate handlers when a shared handler would be simpler

Summary

React 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.

Key Takeaways
  • Forms in React are usually handled with controlled components.
  • A controlled component stores its current value in React state.
  • Use onChange to keep form fields and state in sync.
  • Use preventDefault() to stop page reload on form submission.
  • Checkboxes use checked instead of value for their state.
  • Validation can run on change, blur, submit, or a combination of these.
  • useRef can be used for uncontrolled fields and file inputs.
  • Large forms can become easier to manage with useReducer.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.