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

Handling Events in React

Learn how to handle button clicks, input changes, form submissions, and other user actions using simple React event handlers.

1. What Is Event Handling?

Event handling means performing an action when a user interacts with an application. In React, we use event handler functions to respond to these actions.

For example, when a user clicks a button, we can display a message, update a counter, or open another section.

Simple Example:
HandlingEvents.jsx JSX
function HandlingEvents() {
    function handleClick() {
        alert("Button clicked successfully!");
    }

    return (
        <button onClick={handleClick}>
            Click Me
        </button>
    );
}

export default HandlingEvents;

Explanation: When the user clicks the button, React calls handleClick() and displays an alert.

Expected Output

Clicking the button displays an alert message.

2. Handling Click Events

A click event occurs when a user clicks an element. In React, the onClick prop handles this event.

ClickEvent.jsx JSX
function ClickEvent() {
    function showMessage() {
        console.log("Welcome to CIIT!");
    }

    return (
        <button onClick={showMessage}>
            Show Message
        </button>
    );
}

export default ClickEvent;

Simple Explanation: The function showMessage runs only when the user clicks the button.

Expected Console Output
> Welcome to CIIT!

3. Handling Events with State

We can use an event handler to update a component's state. When state changes, React updates the relevant UI.

Counter.jsx JSX
import { useState } from "react";

function Counter() {
    const [count, setCount] = useState(0);

    function handleClick() {
        setCount(previousCount => previousCount + 1);
    }

    return (
        <div>
            <h3>Count: {count}</h3>

            <button onClick={handleClick}>
                Increase
            </button>
        </div>
    );
}

export default Counter;
Simple Explanation:
  • useState(0) starts the count at zero.
  • handleClick() runs after the button is clicked.
  • setCount() increases the count by one.
  • React displays the updated count.
Interactive Output

Counter Demo

0

Click Increase to change the count.

4. Handling Input Change Events

The onChange event handles changes in an input field. It is commonly used when users enter text or select a value.

NameInput.jsx JSX
import { useState } from "react";

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

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

    return (
        <div>
            <input
                type="text"
                value={name}
                onChange={handleChange}
                placeholder="Enter your name"
            />

            <p>Your name: {name}</p>
        </div>
    );
}

export default NameInput;
Simple Explanation: event.target.value gets the current input value. setName() saves that value in React state.
Interactive Input Preview
Your name:

5. Handling Form Submit Events

The onSubmit event handles form submission. We commonly use event.preventDefault() to stop the browser from reloading the page when a form is submitted.

StudentForm.jsx JSX
function StudentForm() {
    function handleSubmit(event) {
        event.preventDefault();
        alert("Form submitted successfully!");
    }

    return (
        <form onSubmit={handleSubmit}>
            <input
                type="text"
                placeholder="Enter student name"
                required
            />

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

export default StudentForm;
Simple Explanation: The user enters a name and clicks Submit. handleSubmit() handles the form submission. preventDefault() prevents the browser's normal form submission behavior.
Interactive Form Preview
Your result will appear here.

6. Passing Arguments to Event Handlers

Sometimes we need to pass a value to an event handler. We can use an arrow function to pass that value when the event occurs.

CourseButton.jsx JSX
function CourseButton() {
    function showCourse(courseName) {
        alert("Selected course: " + courseName);
    }

    return (
        <button
            onClick={() => showCourse("React Development")}>
            View Course
        </button>
    );
}

export default CourseButton;
Simple Explanation: The arrow function waits for the click. When the user clicks, it passes "React Development" to showCourse().
Expected Output

Clicking the button displays: Selected course: React Development

7. Handling Keyboard Events

Keyboard events allow us to respond when a user presses a key. The onKeyDown prop can handle key presses.

KeyboardEvent.jsx JSX
function KeyboardEvent() {
    function handleKeyDown(event) {
        if (event.key === "Enter") {
            console.log("Enter key pressed!");
        }
    }

    return (
        <input
            type="text"
            onKeyDown={handleKeyDown}
            placeholder="Press Enter"
        />
    );
}

export default KeyboardEvent;
Simple Explanation: The handler checks which key was pressed. If the key is Enter, the message is logged in the console.
Interactive Keyboard Preview
Waiting for Enter key...

8. Common Mistakes

1. Calling the handler immediately
// Incorrect for ordinary click handling
<button onClick={handleClick()}>
    Click
</button>

// Correct
<button onClick={handleClick}>
    Click
</button>

Pass the function reference when it should run after the click.

2. Forgetting preventDefault in a form
function handleSubmit(event) {
    event.preventDefault();
    console.log("Form submitted");
}

Use preventDefault() when you want to prevent the browser's default form submission behavior.

3. Using the wrong event prop
// Correct for input changes
<input onChange={handleChange} />

// Correct for button clicks
<button onClick={handleClick}>
    Click
</button>

Select the event prop that matches the user action.

9. Practice Questions

  1. What is event handling in React?
  2. How do you handle a button click in React?
  3. How can you update state inside an event handler?
  4. What is the purpose of onChange?
  5. Why do we use event.preventDefault() in forms?
  6. How do you pass an argument to an event handler?
  7. Write a component that displays a message when Enter is pressed.
  8. Write a form that displays a success message after submission.

Summary

Event handling allows React components to respond to user actions. Use onClick for clicks, onChange for input changes, onSubmit for forms, and onKeyDown for keyboard input. Event handlers can update state, access event information, and receive arguments. Use preventDefault() when you need to stop the browser's default behavior.