Master React From Scratch

Clear, practical, and structured React lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to React
Introduction to React What Is React? Features of React Advantages of React Limitations of React Uses of React React vs JavaScript React Architecture
2. React Getting Started
Getting Started Introduction Prerequisites Installing Node.js and npm Creating a React Project with Vite React Project Structure Running React Application Your First React Application
3. JSX
JSX Introduction What Is JSX? JavaScript Expressions JSX Attributes Rendering JSX Elements JSX Children React Fragments JSX Rules and Best Practices JSX vs HTML
4. React Components
Components Introduction Functional Components Class Components Component Composition Reusable Components Component Tree Component Lifecycle Import and Export Components
5. React Props
Props Introduction What Are Props? Passing Props to Components Props Destructuring Default Props Values Children Props Typing Props with TypeScript Props vs State
6. React State
State Introduction What Is State? useState Hook Updating State Functional State Updates State with Objects State with Arrays State Immutability Lifting State Up
7. React Events
Events Introduction Handling Events Passing Arguments to Event Handlers Synthetic Events Form Events Keyboard and Mouse Events Event Propagation
8. Conditional Rendering
Conditional Rendering Introduction If-Else Rendering Ternary Operator Logical AND Operator Element Variables Preventing Rendering Multiple Conditions Conditional CSS Classes
9. Lists and Keys
Lists and Keys Introduction Rendering Lists with map() Understanding Keys Choosing Unique Keys Lists of Objects Filtering Lists Sorting Lists Empty Lists and Conditional Rendering
10. React Forms
Forms Introduction Handling Forms Controlled Components Uncontrolled Components Handling Input Fields Checkboxes and Radio Buttons Select and Textarea Form Validation Form Submission
11. React Hooks
Hooks Introduction useState Hook useEffect Hook Effect Dependencies and Cleanup useRef Hook useReducer Hook useMemo Hook useCallback Hook Custom Hooks Rules of Hooks
12. React Context API
Context API Introduction createContext useContext Context Provider Reading Context Updating Context Using Multiple Contexts Context API vs Props Context API Best Practices
13. React Routing
Routing Introduction Introduction to React Router Installing React Router BrowserRouter Setup Routes and Route Components Link and NavLink Programmatic Navigation URL Parameters and useParams Nested Routes Not Found Routes Protected Routes
14. API Integration
API Integration Introduction Fetch API Async/Await with API Calls Displaying API Data Loading and Error States Sending POST Requests API Error Handling Using Axios Custom Fetch Hook API Environment Variables
15. State Management
State Management Introduction Global State Prop Drilling Introduction to Redux Redux Core Concepts Redux Toolkit Store and Slices useSelector and useDispatch Async Operations with Redux Toolkit State Management Best Practices
16. React Performance
Performance Introduction Understanding Re-Renders Avoiding Unnecessary Re-Renders React.memo useMemo Optimization useCallback Optimization React Developer Tools and Profiler Lazy Loading Components Code Splitting Optimizing Large Lists Performance Best Practices

1. Introduction to Handling Forms

Handling forms means collecting information entered by users and deciding what to do with that information. For example, a registration form collects a student's name, email address, and other details.

In React, we commonly use state to store input values and event handlers to respond when users change fields or submit the form.

Remember: React form handling commonly uses useState, onChange, and onSubmit.

2. Creating a Basic Form

A basic form can contain input fields and a submit button. The onSubmit event handler lets the component respond when the user submits the form.

Example

function StudentForm() {
    function handleSubmit(event) {
        event.preventDefault();

        console.log("Form submitted");
    }

    return (
        <form onSubmit={handleSubmit}>
            <label htmlFor="studentName">
                Student Name:
            </label>

            <input
                type="text"
                id="studentName"
                name="studentName"
            />

            <button type="submit">
                Submit
            </button>
        </form>
    );
}

export default StudentForm;

Expected Result

Student Form

When the form is submitted in the running React application, "Form submitted" appears in the console.

The event.preventDefault() method prevents the browser's default form submission behavior. The handler can then process the form using React code.

3. Handling Input Changes

The onChange event runs when the value of an input changes. We can use this event to update a state variable with the value entered by the user.

Example

import { useState } from "react";

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

    function handleChange(event) {
        setName(event.target.value);
    }

    return (
        <div>
            <label htmlFor="name">Name:</label>

            <input
                type="text"
                id="name"
                value={name}
                onChange={handleChange}
            />

            <p>Entered Name: {name}</p>
        </div>
    );
}

export default NameForm;

Expected Output

Entered Name: Rahul

When the user types "Rahul", the onChange handler updates the name state. React then displays the updated value below the input field.

4. Handling Form Submission

The onSubmit event is triggered when a form is submitted. We can use a handler to read stored form values, validate the information, and perform the required action.

Example

import { useState } from "react";

function LoginForm() {
    const [username, setUsername] = useState("");

    function handleSubmit(event) {
        event.preventDefault();

        console.log("Username:", username);
    }

    return (
        <form onSubmit={handleSubmit}>
            <label htmlFor="username">
                Username:
            </label>

            <input
                id="username"
                value={username}
                onChange={(event) =>
                    setUsername(event.target.value)
                }
            />

            <button type="submit">
                Login
            </button>
        </form>
    );
}

export default LoginForm;

Expected Console Output

Username: Rahul

If the user enters "Rahul" and submits the form, the handler logs the username stored in state.

Important: This example demonstrates form handling only. It does not authenticate a user or connect to a server.

5. Handling Multiple Input Fields

A form may contain several input fields. We can store related values in a single state object and update the appropriate property when an input changes.

Example

import { useState } from "react";

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

    function handleChange(event) {
        const { name, value } = event.target;

        setFormData((previousData) => ({
            ...previousData,
            [name]: value
        }));
    }

    function handleSubmit(event) {
        event.preventDefault();

        console.log(formData);
    }

    return (
        <form onSubmit={handleSubmit}>
            <label htmlFor="name">Name:</label>
            <input
                id="name"
                name="name"
                value={formData.name}
                onChange={handleChange}
            />

            <label htmlFor="email">Email:</label>
            <input
                id="email"
                name="email"
                type="email"
                value={formData.email}
                onChange={handleChange}
            />

            <button type="submit">
                Register
            </button>
        </form>
    );
}

export default RegistrationForm;

Expected Console Output

{
    name: "Rahul",
    email: "rahul@example.com"
}

The name attribute identifies which property should be updated. The spread operator preserves the other values already stored in the state object.

6. Displaying Submitted Form Data

After a form is submitted, we can store the submitted information in state and display it on the page. This is useful for showing a confirmation or summary of the information entered by the user.

Example

import { useState } from "react";

function FeedbackForm() {
    const [message, setMessage] = useState("");
    const [submittedMessage, setSubmittedMessage] = useState("");

    function handleSubmit(event) {
        event.preventDefault();
        setSubmittedMessage(message);
    }

    return (
        <div>
            <form onSubmit={handleSubmit}>
                <label htmlFor="message">
                    Feedback:
                </label>

                <input
                    id="message"
                    value={message}
                    onChange={(event) =>
                        setMessage(event.target.value)
                    }
                />

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

            {submittedMessage && (
                <p>
                    Submitted Feedback: {submittedMessage}
                </p>
            )}
        </div>
    );
}

export default FeedbackForm;

Expected Output

Submitted Feedback: Great learning experience!

The submitted message is stored separately from the current input value. After submission, React displays the saved message.

7. Resetting Form Values

After processing a form, we may want to clear the input fields. When form values are controlled by React state, we can reset them by updating the state.

Example

import { useState } from "react";

function CommentForm() {
    const [comment, setComment] = useState("");

    function handleSubmit(event) {
        event.preventDefault();

        console.log("Comment:", comment);
        setComment("");
    }

    return (
        <form onSubmit={handleSubmit}>
            <label htmlFor="comment">
                Comment:
            </label>

            <input
                id="comment"
                value={comment}
                onChange={(event) =>
                    setComment(event.target.value)
                }
            />

            <button type="submit">
                Submit
            </button>
        </form>
    );
}

export default CommentForm;

Expected Result

After submission, the entered comment is logged to the console and the input field becomes empty.

Remember: For a controlled input, update its state to reset the displayed value.

8. Common Mistakes

Mistake 1: Forgetting to Prevent Default Submission

function handleSubmit(event) {
    console.log("Form submitted");
}

The browser may perform its default form submission, which can reload or navigate the page.

Correct Code

function handleSubmit(event) {
    event.preventDefault();

    console.log("Form submitted");
}

Mistake 2: Not Updating the Input State

<input
    value={name}
    onChange={() => {}}
/>

A controlled input needs an event handler that updates its state value. Otherwise, typing will not update the displayed input value.

Correct Code

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

Mistake 3: Replacing Other Properties in State

setFormData({
    [name]: value
});

This replaces the state object with an object containing only the changed property. Other form values can be lost.

Correct Code

setFormData((previousData) => ({
    ...previousData,
    [name]: value
}));

9. Practice Tasks

Complete these tasks to practise handling forms in React.

Task 1: Create a student form with a name input and handle its value using useState.
Task 2: Create a login form with username and password fields. Prevent the browser's default form submission.
Task 3: Create a registration form with name and email fields. Store both values in a state object.
Task 4: Display the submitted feedback message below a form after the user submits it.
Task 5: Create a comment form that clears its input after submission.

Summary

Handling forms in React involves collecting input values, updating state, and processing form submissions using event handlers. The onChange event updates controlled input values, while onSubmit handles the submission process. Multiple input fields can be managed with a state object, submitted information can be displayed using state, and controlled fields can be cleared by resetting their values. These techniques help create interactive forms that can later be extended with validation and server-side processing.