Skip to content
Home Tutorials Roadmaps Courses Classroom Training Blog
Log in Join free
React Intermediate Free

Forms & Controlled Inputs

Lesson 9 of 17 · Routing & Forms 53%
1. Getting Started
What is React?
2. Components & Props
Components & Props
6. Performance & Testing
React.memo & Lazy Loading
7. Custom Hooks
Building Custom Hooks
8. State Management
Context API Redux Basics
9. Error Boundaries
Error Handling
10. Server Components
React Server Components
11. Next.js Introduction
Next.js Basics
12. Animations & Transitions
Framer Motion

Controlled inputs bind form elements to React state.

Syntax

REACT
function Form() {
    const [name, setName] = useState("");
    const handleSubmit = (e) => {
        e.preventDefault();
        alert(`Submitted: ${name}`);
    };
    return (
        <form onSubmit={handleSubmit}>
            <input value={name} onChange={e => setName(e.target.value)} />
            <button type="submit">Submit</button>
        </form>
    );
}
Controlled Forms
REACT
import { useState } from "react";

function Form() {
    const [formData, setFormData] = useState({
        name: "", email: ""
    });

    const handleChange = (e) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        console.log(formData);
    };

    return (
        <form onSubmit={handleSubmit}>
            <input name="name" value={formData.name}
                   onChange={handleChange} placeholder="Name" />
            <input name="email" value={formData.email}
                   onChange={handleChange} placeholder="Email" />
            <button type="submit">Submit</button>
        </form>
    );
}

Practice

1
Exercise

Practice this concept.

Answer
Write the code as shown above.

Quick Quiz

1

What did you learn?

This covers the basics.

Choose an answer to continue.

Interview Questions

It is a fundamental React feature.

Up next

React.memo & Lazy Loading

Lesson 10 of 17 · Performance & Testing