Lesson 26 of 60 – Forms in React
43%

Forms in React

Forms are used to collect information from users. In React, forms can be created using normal HTML form elements such as <input>, <textarea>, <select>, and <button>. React can manage the values entered by users using state and event handlers.

Note: React forms commonly use event handlers such as onChange and onSubmit to manage user input.

1. What is a Form?

A form is a user interface element used to collect information from users.

Examples include:

  • Login forms
  • Registration forms
  • Contact forms
  • Admission forms
  • Search forms
  • Feedback forms
<form>

    <input type="text" />

    <button type="submit">
        Submit
    </button>

</form>

2. Forms in React

React uses the same basic HTML form elements, but JavaScript and React events can be used to control their behavior.

function App() {

    return (
        <form>

            <input type="text" />

            <button type="submit">
                Submit
            </button>

        </form>
    );

}

export default App;

3. Input Element

The <input> element is commonly used to collect short pieces of information.

<input
    type="text"
    placeholder="Enter your name"
/>

Common input types include:

  • text
  • email
  • password
  • number
  • date
  • checkbox
  • radio

4. Text Input

A text input can be used to collect information such as a name.

function App() {

    return (
        <div>

            <label>
                Name:
            </label>

            <input type="text" />

        </div>
    );

}

5. Using useState for Form Input

React state can be used to store the value entered into an input.

import { useState } from "react";

function App() {

    const [name, setName] = useState("");

    return (
        <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
        />
    );

}

Here, name stores the current input value.

6. The onChange Event

The onChange event runs when the value of an input changes.

function App() {

    const [name, setName] = useState("");

    return (
        <input
            value={name}
            onChange={(e) => setName(e.target.value)}
        />
    );

}

Every time the user changes the input, the state can be updated.

7. Reading Input Value

The current input value can be accessed using e.target.value.

function handleChange(e) {

    console.log(e.target.value);

}

The target represents the form element that triggered the event.

8. Displaying Input Value

A value stored in state can be displayed on the screen.

import { useState } from "react";

function App() {

    const [name, setName] = useState("");

    return (
        <div>

            <input
                value={name}
                onChange={(e) => setName(e.target.value)}
            />

            <h2>
                Hello {name}
            </h2>

        </div>
    );

}

9. Form Submit

A form can be submitted using a button with type="submit".

<form>

    <input type="text" />

    <button type="submit">
        Submit
    </button>

</form>

10. The onSubmit Event

React provides the onSubmit event for handling form submission.

function App() {

    function handleSubmit(e) {

        e.preventDefault();

        console.log("Form submitted");

    }

    return (
        <form onSubmit={handleSubmit}>

            <input type="text" />

            <button type="submit">
                Submit
            </button>

        </form>
    );

}

11. preventDefault()

Normally, submitting an HTML form can cause a browser navigation or page reload. In React, e.preventDefault() can be used to prevent the browser's default form submission behavior.

function handleSubmit(e) {

    e.preventDefault();

    console.log("Form submitted");

}

12. Complete Simple Form

import { useState } from "react";

function App() {

    const [name, setName] = useState("");

    function handleSubmit(e) {

        e.preventDefault();

        alert("Hello " + name);

    }

    return (
        <form onSubmit={handleSubmit}>

            <input
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="Enter your name"
            />

            <button type="submit">
                Submit
            </button>

        </form>
    );

}

export default App;

13. Email Input

The email input type can be used for email addresses.

const [email, setEmail] = useState("");

<input
    type="email"
    value={email}
    onChange={(e) => setEmail(e.target.value)}
    placeholder="Enter email"
/>

14. Password Input

A password field hides the characters typed by the user.

const [password, setPassword] = useState("");

<input
    type="password"
    value={password}
    onChange={(e) => setPassword(e.target.value)}
    placeholder="Enter password"
/>

15. Number Input

A number input can be used to collect numeric information.

const [age, setAge] = useState("");

<input
    type="number"
    value={age}
    onChange={(e) => setAge(e.target.value)}
/>

16. Textarea

The <textarea> element is useful when users need to enter multiple lines of text.

const [message, setMessage] = useState("");

<textarea
    value={message}
    onChange={(e) => setMessage(e.target.value)}
    placeholder="Enter your message"
/>

17. Select Element

A <select> element allows users to choose an option from a list.

const [course, setCourse] = useState("");

<select
    value={course}
    onChange={(e) => setCourse(e.target.value)}
>

    <option value="">
        Select Course
    </option>

    <option value="react">
        React
    </option>

    <option value="python">
        Python
    </option>

</select>

18. Checkbox

A checkbox can be controlled using a boolean state value.

const [agree, setAgree] = useState(false);

<label>

    <input
        type="checkbox"
        checked={agree}
        onChange={(e) => setAgree(e.target.checked)}
    />

    I agree to the terms

</label>

19. Radio Buttons

Radio buttons allow users to choose one option from a group.

const [gender, setGender] = useState("");

<label>
    <input
        type="radio"
        name="gender"
        value="male"
        checked={gender === "male"}
        onChange={(e) => setGender(e.target.value)}
    />

    Male
</label>

<label>
    <input
        type="radio"
        name="gender"
        value="female"
        checked={gender === "female"}
        onChange={(e) => setGender(e.target.value)}
    />

    Female
</label>

20. Multiple Form Fields

A form can contain multiple fields. Each field can have its own state.

const [name, setName] = useState("");
const [email, setEmail] = useState("");

<input
    value={name}
    onChange={(e) => setName(e.target.value)}
/>

<input
    value={email}
    onChange={(e) => setEmail(e.target.value)}
/>

21. Form State as an Object

Multiple form fields can also be stored inside one state object.

const [form, setForm] = useState({
    name: "",
    email: ""
});

This approach can be useful for larger forms.

22. Updating Object Form State

function handleChange(e) {

    setForm({
        ...form,
        [e.target.name]: e.target.value
    });

}

The spread operator keeps the existing form values while updating the field that changed.

23. Form Field Names

When using one state object, the name attribute can be used to identify each form field.

<input
    name="name"
    value={form.name}
    onChange={handleChange}
/>

<input
    name="email"
    value={form.email}
    onChange={handleChange}
/>

24. Handling Checkbox State

Checkboxes normally use checked and e.target.checked because their value represents a boolean state.

const [isStudent, setIsStudent] = useState(false);

<input
    type="checkbox"
    checked={isStudent}
    onChange={(e) => setIsStudent(e.target.checked)}
/>

25. Showing Submitted Data

After submission, the collected form data can be displayed or sent to another function or service.

function handleSubmit(e) {

    e.preventDefault();

    console.log("Name:", form.name);
    console.log("Email:", form.email);

}

26. Resetting a Form

After successful submission, state can be reset to clear the form.

function handleSubmit(e) {

    e.preventDefault();

    console.log(form);

    setForm({
        name: "",
        email: ""
    });

}

27. Basic Form Validation

Before submitting a form, you can check whether required values have been entered.

function handleSubmit(e) {

    e.preventDefault();

    if (form.name === "") {

        alert("Name is required");
        return;

    }

    console.log("Form submitted");

}

28. Complete Registration Form

import { useState } from "react";

function App() {

    const [form, setForm] = useState({
        name: "",
        email: "",
        course: ""
    });

    function handleChange(e) {

        setForm({
            ...form,
            [e.target.name]: e.target.value
        });

    }

    function handleSubmit(e) {

        e.preventDefault();

        if (!form.name || !form.email || !form.course) {

            alert("Please fill all fields");
            return;

        }

        console.log(form);

    }

    return (
        <form onSubmit={handleSubmit}>

            <input
                name="name"
                value={form.name}
                onChange={handleChange}
                placeholder="Name"
            />

            <br />

            <input
                name="email"
                value={form.email}
                onChange={handleChange}
                placeholder="Email"
            />

            <br />

            <select
                name="course"
                value={form.course}
                onChange={handleChange}
            >

                <option value="">
                    Select Course
                </option>

                <option value="react">
                    React
                </option>

                <option value="python">
                    Python
                </option>

            </select>

            <br />

            <button type="submit">
                Register
            </button>

        </form>
    );

}

export default App;

29. Controlled Form Elements

A controlled form element gets its current value from React state and updates that state when the user changes the field.

const [name, setName] = useState("");

<input
    value={name}
    onChange={(e) => setName(e.target.value)}
/>

This gives React control over the current value of the input.

30. React Forms Best Practices

  • Use meaningful names for form fields.
  • Use onChange to update controlled inputs.
  • Use onSubmit to handle form submission.
  • Use preventDefault() when appropriate.
  • Validate important form data before processing it.
  • Use checked for controlled checkboxes.
  • Use e.target.checked to read checkbox state.
  • Use value for controlled text inputs.
  • Use state to keep track of user input.
  • Reset form state after a successful submission when needed.

📌 Key Points

  • React forms use normal HTML form elements.
  • State can be used to store form values.
  • onChange handles changes in form fields.
  • onSubmit handles form submission.
  • preventDefault() prevents the browser's default submission behavior.
  • Inputs can be controlled using React state.
  • Checkboxes commonly use checked and e.target.checked.
  • Select elements can be controlled using value.
  • Multiple fields can be stored in one state object.
  • Form validation can be performed before submission.

🧠 Quick Quiz

Question: Which React event is commonly used to handle form submission?