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 Checkboxes and Radio Buttons

Checkboxes and radio buttons are form elements used to collect choices from users. A checkbox allows users to select or deselect an option. Radio buttons allow users to select one option from a group.

In React, we can manage these selections using state. The checked prop determines whether an option is selected, and the onChange handler updates the state.

Remember: Use checked to control the selected state of a checkbox or radio button. Use onChange to respond to changes.

2. Understanding the Difference

Feature Checkbox Radio Button
Purpose Select or deselect an option. Select one option from a group.
Multiple selections Multiple options can be selected. Only one option in the same group can be selected.
React prop checked checked
Common use Accepting terms or selecting interests. Selecting a course or payment method.
Example: A student can select multiple course interests using checkboxes, but can choose one preferred batch using radio buttons.

3. Creating a Controlled Checkbox

A controlled checkbox uses React state to store whether the checkbox is selected. The event.target.checked property gives the current checked value.

Example

import { useState } from "react";

function TermsCheckbox() {
    const [accepted, setAccepted] = useState(false);

    function handleChange(event) {
        setAccepted(event.target.checked);
    }

    return (
        <div>
            <label>
                <input
                    type="checkbox"
                    checked={accepted}
                    onChange={handleChange}
                />

                I accept the terms and conditions
            </label>

            <p>
                Accepted: {accepted ? "Yes" : "No"}
            </p>
        </div>
    );
}

export default TermsCheckbox;

Expected Output

Accepted: No

Initially, the checkbox is unchecked because accepted is false. When the user selects it, the state becomes true and the displayed message changes to Yes.

4. Selecting Multiple Options with Checkboxes

Sometimes users need to select more than one option. We can store the selected options in an array and update that array when a checkbox changes.

Example: Course Interests

import { useState } from "react";

function CourseInterests() {
    const [courses, setCourses] = useState([]);

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

        if (checked) {
            setCourses((previousCourses) => [
                ...previousCourses,
                value
            ]);
        } else {
            setCourses((previousCourses) =>
                previousCourses.filter(
                    (course) => course !== value
                )
            );
        }
    }

    return (
        <div>
            <h3>Select Course Interests</h3>

            <label>
                <input
                    type="checkbox"
                    value="React"
                    checked={courses.includes("React")}
                    onChange={handleChange}
                />
                React
            </label>

            <label>
                <input
                    type="checkbox"
                    value="Angular"
                    checked={courses.includes("Angular")}
                    onChange={handleChange}
                />
                Angular
            </label>

            <label>
                <input
                    type="checkbox"
                    value="Python"
                    checked={courses.includes("Python")}
                    onChange={handleChange}
                />
                Python
            </label>

            <p>Selected Courses: {courses.join(", ")}</p>
        </div>
    );
}

export default CourseInterests;

Expected Output

Select Course Interests

Selected Courses: React, Angular

The courses array stores selected values. When a user checks an option, its value is added. When an option is unchecked, filter() removes that value from the array.

Important: The spread operator creates a new array when adding a selection. React state should be updated rather than modifying the existing array directly.

5. Creating Radio Buttons

Radio buttons are used when a user must select one option from a group. Give related radio buttons the same name attribute and manage the selected value using state.

Example: Preferred Batch

import { useState } from "react";

function BatchSelection() {
    const [batch, setBatch] = useState("Morning");

    return (
        <div>
            <h3>Choose Your Preferred Batch</h3>

            <label>
                <input
                    type="radio"
                    name="batch"
                    value="Morning"
                    checked={batch === "Morning"}
                    onChange={(event) =>
                        setBatch(event.target.value)
                    }
                />
                Morning
            </label>

            <label>
                <input
                    type="radio"
                    name="batch"
                    value="Evening"
                    checked={batch === "Evening"}
                    onChange={(event) =>
                        setBatch(event.target.value)
                    }
                />
                Evening
            </label>

            <p>Selected Batch: {batch}</p>
        </div>
    );
}

export default BatchSelection;

Expected Output

Choose Your Preferred Batch

Selected Batch: Morning

The batch state stores the selected option. Choosing Evening updates the state to Evening, and React displays the new selection.

6. CIIT Training Institute Course Registration Example

Consider a student named Samadhan Samiksha who wants to register for a course at CIIT Training Institute. The form below demonstrates how a checkbox and radio buttons can be used together.

Example

import { useState } from "react";

function CIITRegistration() {
    const [studentName, setStudentName] =
        useState("Samadhan Samiksha");

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

    const [termsAccepted, setTermsAccepted] =
        useState(false);

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

        console.log({
            studentName,
            course,
            termsAccepted
        });
    }

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

            <label htmlFor="studentName">
                Student Name:
            </label>

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

            <p>Select a Course:</p>

            <label>
                <input
                    type="radio"
                    name="course"
                    value="React"
                    checked={course === "React"}
                    onChange={(event) =>
                        setCourse(event.target.value)
                    }
                />
                React
            </label>

            <label>
                <input
                    type="radio"
                    name="course"
                    value="Angular"
                    checked={course === "Angular"}
                    onChange={(event) =>
                        setCourse(event.target.value)
                    }
                />
                Angular
            </label>

            <label>
                <input
                    type="checkbox"
                    checked={termsAccepted}
                    onChange={(event) =>
                        setTermsAccepted(event.target.checked)
                    }
                />
                I confirm my registration details.
            </label>

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

export default CIITRegistration;

Expected Console Output

{
    studentName: "Samadhan Samiksha",
    course: "React",
    termsAccepted: false
}

This example stores the student name, selected course, and checkbox status in React state. Submitting the form logs the current values to the console. It demonstrates form handling only and does not save registration data to a database.

CIIT Training Institute: Practical examples help learners understand how React form controls can be used in course registration forms.

7. Handling Checkbox and Radio Button Events

For checkboxes, use event.target.checked to read whether the option is selected. For radio buttons, use event.target.value to read the selected option.

Checkbox Handler

function handleCheckboxChange(event) {
    setAccepted(event.target.checked);
}

Radio Button Handler

function handleRadioChange(event) {
    setCourse(event.target.value);
}
Property Meaning Common use
event.target.checked Returns true or false. Checkbox selection
event.target.value Returns the selected value. Radio button selection

8. Common Mistakes

Mistake 1: Using checked Without Updating State

<input
    type="checkbox"
    checked={accepted}
/>

The checkbox is controlled by accepted, but no handler updates that state when the user interacts with it.

Correct Code

<input
    type="checkbox"
    checked={accepted}
    onChange={(event) =>
        setAccepted(event.target.checked)
    }
/>

Mistake 2: Using Different Names for One Radio Group

<input type="radio" name="morning" value="Morning" />
<input type="radio" name="evening" value="Evening" />

Different name attributes create separate radio groups, so the browser may allow both options to be selected.

Correct Code

<input type="radio" name="batch" value="Morning" />
<input type="radio" name="batch" value="Evening" />

Mistake 3: Reading the Wrong Event Property

setAccepted(event.target.value);

A checkbox's selected status is represented by its checked property, not its value property.

Correct Code

setAccepted(event.target.checked);

9. Practice Tasks

Complete these tasks to practise checkboxes and radio buttons.

Task 1: Create a checkbox that displays Yes when selected and No when unselected.
Task 2: Create three course-interest checkboxes for React, Angular, and Python. Display all selected courses.
Task 3: Create radio buttons for Morning and Evening batches. Display the selected batch.
Task 4: Create a CIIT Training Institute registration form that uses the name Samadhan Samiksha and lets a student select a course and accept a confirmation checkbox.
Task 5: Submit a form and display the selected course and checkbox status in the browser console.

Summary

Checkboxes and radio buttons collect selections from users in React forms. A checkbox can be selected or deselected, and multiple checkboxes can be managed using an array in state. Radio buttons with the same name allow the user to choose one option from a group. The checked prop controls selection, event.target.checked reads checkbox status, and event.target.value reads the selected radio option. These techniques can be used to build course registration forms and other interactive form interfaces at CIIT Training Institute.