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

React Events Introduction

Learn how React handles user interactions such as button clicks, keyboard input, form changes, and submissions with practical examples.

1. What Are Events in React?

An event is an action performed by a user or triggered by the browser. Examples include clicking a button, typing text, submitting a form, and moving the mouse.

React event handlers allow components to respond to these actions by executing JavaScript functions.

Example: Welcome Button
Welcome.jsx JSX
function Welcome() {
    function showMessage() {
        alert("Welcome to CIIT Training Institute!");
    }

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

export default Welcome;
Expected Output

Clicking the button displays a welcome alert.

2. Why Are Events Important?

Events make React applications interactive. They allow users to perform actions and receive responses from the application.

🖱️

Mouse Events

Handle button clicks and mouse interactions.

onClick
⌨️

Keyboard Events

Respond when users press keyboard keys.

onKeyDown
📝

Form Events

Handle input changes and form submissions.

onChange
🎯

Focus Events

Respond when an input gains or loses focus.

onFocus
Real-world example: A student registers for a course. React handles the student's input, button clicks, and form submission using event handlers.

3. How Do React Events Work?

When an event occurs, React calls the function associated with the corresponding event prop.

Step 1
User Action

Click a button

↓
Step 2
Event Occurs

React handles the interaction

↓
Step 3
Function Executes

The event handler runs

↓
Step 4
Output Appears

The application responds

EventFlow.jsx JSX
function EventFlow() {
    function handleClick() {
        console.log("Button clicked!");
    }

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

export default EventFlow;
Expected Console Output
> Button clicked!
Important: onClick={handleClick} passes the function reference. onClick={handleClick()} calls the function immediately during rendering.

4. React Event Naming Convention

React uses camelCase event props. In JSX, event handlers are passed using curly braces.

Event Prop Purpose Example
onClick Handles clicks Button click
onChange Handles value changes Typing in an input
onSubmit Handles form submission Submitting a form
onKeyDown Handles key presses Pressing Enter
onMouseOver Handles mouse-over events Moving over an element
onFocus Handles focus Selecting an input
✓ Correct in React JSX
<button onClick={handleClick}>
    Click Me
</button>
✗ Incorrect for React JSX
<button onclick={handleClick}>
    Click Me
</button>

5. Passing a Function to an Event

Pass the function reference when the function should execute after the event occurs.

FunctionHandler.jsx JSX
function FunctionHandler() {
    function handleClick() {
        alert("Button clicked successfully!");
    }

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

export default FunctionHandler;
Expected Output

A button appears. Clicking it displays:

Button clicked successfully!
Remember: Use onClick={handleClick} to pass a handler. Use onClick={() => handleClick()} when you need to execute additional code or pass arguments later.

6. Understanding the Event Object

React passes an event object to the handler. It contains information about the event and the element involved.

EventObject.jsx JSX
function EventObject() {
    function handleClick(event) {
        console.log("Event type:", event.type);
        console.log("Clicked element:", event.target);
    }

    return (
        <button onClick={handleClick}>
            Inspect Event
        </button>
    );
}

export default EventObject;
Expected Console Output After Clicking
> Event type: click
> Clicked element: button element
Property / Method Description
event.type Identifies the event type.
event.target Identifies the element that triggered the event.
event.currentTarget Identifies the element whose handler is running.
event.preventDefault() Prevents the browser's default action.
event.stopPropagation() Stops further event propagation.

7. Practical Example — Click Counter

In this example, clicking the button increases the count. The React code uses useState() to store the count.

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

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

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

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

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

export default ClickCounter;
Interactive Output Preview

CIIT Click Counter

0

Click the button and observe the counter.

Expected Output: The counter starts at 0. Each click increases the count by one. The Reset button in this lesson preview returns it to zero.

Note: The preview uses JavaScript to demonstrate the result. The code shown above is the React implementation.

8. Common Mistakes in React Events

1. Using lowercase event names
// Incorrect
<button onclick={handleClick}>Click</button>

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

// Correct
<button onClick={handleClick}>Click</button>
3. Passing a string instead of a function
// Incorrect
<button onClick="handleClick">Click</button>

// Correct
<button onClick={handleClick}>Click</button>
Best Practice: Use descriptive function names such as handleClick, handleSubmit, and handleChange.

9. Practice Questions

  1. What is an event in React?
  2. Why do React applications need event handlers?
  3. What is the purpose of the onClick prop?
  4. Why should we pass a function reference to an event handler?
  5. What is the React event object?
  6. Explain the purpose of onChange and onSubmit.
  7. Write a component that displays an alert when a button is clicked.
  8. Write a component that increases a counter on each click.

Summary

React events make components interactive by connecting user actions to JavaScript functions. Event props use camelCase, and handlers are passed using JSX expressions. The event object provides useful information about an interaction. Understanding event handling is essential for building responsive React applications.