Chapter 6: Handling Events

1. Event Handling in React – The Basics

In plain HTML/JavaScript, we write event handlers like this:

HTML

In React → we do it differently (and much cleaner):

  • We use camelCase event names: onClick, onChange, onSubmit, onMouseOver, etc.
  • We pass a function reference (not a string)
  • React handles event delegation behind the scenes (super efficient)

Golden Rule: Do NOT call the function immediately with () inside the JSX — that runs it instantly!

Wrong (runs immediately on render) Correct (runs only on click)
<button onClick={handleClick()}> <button onClick={handleClick}>
<button onClick={alert(‘hi’)}> <button onClick={() => alert(‘hi’)}>

2. Common Events in React

Here are the most used ones:

Event Name Triggered When… Example Usage
onClick User clicks (mouse or tap) Buttons, cards
onChange Input, select, textarea value changes Forms, search bars
onSubmit Form is submitted (Enter or button) Login, signup forms
onKeyDown Key is pressed down Enter key detection
onKeyUp Key is released Typing games
onMouseEnter Mouse enters element Hover effects
onMouseLeave Mouse leaves element Hover effects
onFocus Element gains focus Input focus styles
onBlur Element loses focus Validation on blur

3. Basic onClick Example

Let’s create a simple Like Button component.

Create src/components/LikeButton.tsx

tsx

Use in App.tsx:

tsx

4. Passing Arguments to Event Handlers

There are 3 clean ways to pass extra data:

Way 1: Arrow function (most common & recommended)

tsx

Way 2: Bind (older style, still works)

tsx

Way 3: Wrapper function (good for complex logic)

tsx

Realistic Example: Like a specific post

tsx

5. onChange – Making Forms Interactive

Let’s build a live search input that shows what you type.

tsx

6. onSubmit – Handling Form Submission

tsx

Summary – Chapter 6 Key Takeaways

  • Use camelCase event names: onClick, onChange, onSubmit
  • Pass function reference → onClick={handleClick} (NOT handleClick())
  • Use arrow function to pass arguments → () => handleLike(id)
  • e.preventDefault() is crucial for forms to stop page reload
  • onChange + value + setState = controlled inputs
  • Every component can have its own event handlers and state

Mini Homework

  1. Create a CounterWithButtons component with:
    • +1, +5, +10 buttons
    • Reset button
    • Show current count
  2. Bonus: Add a ColorPicker with 3 buttons (Red, Green, Blue) that change the background color of a box using state.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *