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 Form Validation

Form validation checks whether the information entered by a user meets the required conditions before a form is submitted. It helps prevent missing or incorrectly formatted information.

In React, validation can be performed using state, conditional rendering, and event handlers. For example, a registration form may require a student name and a valid email address.

Remember: Client-side validation improves the user experience, but important validation must also be performed on the server.

2. Required Field Validation

Required field validation checks whether the user has entered a value. We can use the trim() method to remove leading and trailing spaces before checking the input.

Example

import { useState } from "react";

function NameValidation() {
    const [name, setName] = useState("");
    const [error, setError] = useState("");

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

        if (name.trim() === "") {
            setError("Name is required.");
            return;
        }

        setError("");
        alert("Form submitted successfully!");
    }

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

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

            {error && <p>{error}</p>}

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

export default NameValidation;

Expected Output

Name is required.

If the user submits the form without entering a name, the error message is displayed. When a name is entered, the error is cleared.

3. Email Validation

Email validation checks whether an entered email address follows an expected format. The following example uses a simple regular expression for basic client-side checking.

Example

import { useState } from "react";

function EmailValidation() {
    const [email, setEmail] = useState("");
    const [error, setError] = useState("");

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

        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        if (!emailPattern.test(email)) {
            setError("Please enter a valid email address.");
            return;
        }

        setError("");
        alert("Email is valid!");
    }

    return (
        <form onSubmit={handleSubmit}>
            <label htmlFor="email">Email Address:</label>

            <input
                id="email"
                type="email"
                value={email}
                onChange={(event) => {
                    setEmail(event.target.value);
                    setError("");
                }}
            />

            {error && <p>{error}</p>}

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

export default EmailValidation;

Expected Output

Please enter a valid email address.

If the email does not match the expected format, the component displays an error message. This is a basic format check, not proof that the address exists.

4. Password Length Validation

Password validation can check whether a password meets a minimum length requirement. The example below requires at least eight characters.

Example

import { useState } from "react";

function PasswordValidation() {
    const [password, setPassword] = useState("");
    const [error, setError] = useState("");

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

        if (password.length < 8) {
            setError("Password must contain at least 8 characters.");
            return;
        }

        setError("");
        alert("Password length is valid.");
    }

    return (
        <form onSubmit={handleSubmit}>
            <label htmlFor="password">Password:</label>

            <input
                id="password"
                type="password"
                value={password}
                onChange={(event) => {
                    setPassword(event.target.value);
                    setError("");
                }}
            />

            {error && <p>{error}</p>}

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

export default PasswordValidation;

Expected Output

Password must contain at least 8 characters.

Security note: Never display or log actual passwords. Real applications should enforce appropriate password rules securely on the server as well.

5. Validating Multiple Fields

A form may need to validate multiple fields before submission. We can check each field and store its validation message in state.

Example: Student Registration

import { useState } from "react";

function StudentRegistration() {
    const [name, setName] = useState("");
    const [email, setEmail] = useState("");
    const [errors, setErrors] = useState({});

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

        const newErrors = {};

        if (name.trim() === "") {
            newErrors.name = "Name is required.";
        }

        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        if (!emailPattern.test(email)) {
            newErrors.email = "Enter a valid email address.";
        }

        setErrors(newErrors);

        if (Object.keys(newErrors).length === 0) {
            alert("Registration form is valid.");
        }
    }

    return (
        <form onSubmit={handleSubmit}>
            <label htmlFor="name">Student Name:</label>
            <input
                id="name"
                value={name}
                onChange={(event) => setName(event.target.value)}
            />
            {errors.name && <p>{errors.name}</p>}

            <label htmlFor="email">Email Address:</label>
            <input
                id="email"
                type="email"
                value={email}
                onChange={(event) => setEmail(event.target.value)}
            />
            {errors.email && <p>{errors.email}</p>}

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

export default StudentRegistration;

Expected Output

Name is required.

Enter a valid email address.

The form checks both fields and stores any errors in the errors object. Submission succeeds only when no validation errors remain.

6. CIIT Training Institute Registration Example

Samadhan wants to register for a course at CIIT Training Institute. This example validates the student's name and email before showing a successful submission message.

Example

import { useState } from "react";

function CIITRegistration() {
    const [name, setName] = useState("Samadhan");
    const [email, setEmail] = useState("");
    const [message, setMessage] = useState("");

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

        if (name.trim() === "") {
            setMessage("Please enter your name.");
            return;
        }

        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        if (!emailPattern.test(email)) {
            setMessage("Please enter a valid email.");
            return;
        }

        setMessage(
            "Thank you, " + name +
            "! Your form passed client-side validation."
        );
    }

    return (
        <form onSubmit={handleSubmit}>
            <h2>CIIT Training Institute</h2>

            <label htmlFor="studentName">Student Name:</label>
            <input
                id="studentName"
                value={name}
                onChange={(event) => setName(event.target.value)}
            />

            <label htmlFor="studentEmail">Email Address:</label>
            <input
                id="studentEmail"
                type="email"
                value={email}
                onChange={(event) => setEmail(event.target.value)}
            />

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

            {message && <p>{message}</p>}
        </form>
    );
}

export default CIITRegistration;

Expected Output

Thank you, Samadhan! Your form passed client-side validation.

When valid values are entered, the form displays a confirmation message. This demonstration does not save the registration to a database or submit it to CIIT Training Institute.

CIIT Training Institute: Learning validation through practical registration examples helps students understand how to check user input before submitting a form.

7. Displaying Error and Success Messages

Conditional rendering allows React to display an error message only when validation fails. A success message can be displayed when all required checks pass.

Example

{error && (
    <p className="error-message">
        {error}
    </p>
)}

{success && (
    <p className="success-message">
        {success}
    </p>
)}

When error contains a message, React renders the error paragraph. When success contains a message, React renders the success paragraph.

Tip: Keep messages clear and specific so users understand what they need to correct.

8. Common Mistakes

Mistake 1: Not Preventing Default Submission

function handleSubmit(event) {
    if (name.trim() === "") {
        setError("Name is required.");
    }
}

Without preventDefault(), a browser form submission may reload or navigate away from the page before the expected React behavior completes.

Correct Code

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

    if (name.trim() === "") {
        setError("Name is required.");
        return;
    }
}

Mistake 2: Checking Only for an Empty String

if (name === "") {
    setError("Name is required.");
}

A value containing only spaces is not an empty string. Using trim() checks whether any non-whitespace text remains.

Correct Code

if (name.trim() === "") {
    setError("Name is required.");
}

Mistake 3: Showing Success Despite Validation Errors

setErrors(newErrors);
alert("Form submitted successfully!");

The form should not show success when validation has failed. Check the validation result before proceeding.

Correct Code

if (Object.keys(newErrors).length === 0) {
    alert("Form submitted successfully!");
}

9. Practice Tasks

Complete these tasks to practise form validation in React.

Task 1: Create a student name field and show an error if it is empty.
Task 2: Validate an email address using a basic regular expression.
Task 3: Check that a password contains at least eight characters.
Task 4: Create a registration form with name and email validation.
Task 5: Create a CIIT Training Institute registration example using the student name Samiksha and display a success message only when the entered fields are valid.

Summary

Form validation checks user input before a form is processed. React can use state, event handlers, and conditional rendering to validate required fields, check email formats, enforce password length rules, and display error or success messages. Multiple field errors can be stored in an object and checked before allowing a successful result. Client-side validation improves usability, while server-side validation remains necessary for application security and data integrity. These techniques can be practised through student registration forms at CIIT Training Institute.