Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials React Forms & Controlled Inputs
React Intermediate FREE

Forms & Controlled Inputs

Lesson 2 of 17 Intermediate Interactive

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.

Interview Questions

It is a fundamental React feature.