Skip to Content

Module 3.2: Event Handling & Child-Parent Communication

Module banner for Event Handling & Child-Parent Communication

🎯 Learning Objectives

By the end of this lesson, you’ll master:

  • Event Handling Syntax: The standard React way to capture events (onClick, onChange, onSubmit).
  • Synthetic Event: Understand how React’s e event object differs from a native DOM Event.
  • Child-to-Parent Communication: The technique of passing a function via props to allow a child component to send signals back up to its parent component.
  • Basic Form Handling: How to control inputs and handle form submissions.

1. Event Handling in React

1.1. Basic Syntax

React handles events very similarly to native DOM elements, but with two key syntactical differences:

  1. Events use camelCase (e.g., onClick instead of onclick).
  2. You pass a function reference within curly braces {}, not a string.

HTML:

<button onclick="activateLasers()">Activate Lasers</button>

React:

<button onClick={activateLasers}>Activate Lasers</button>

1.2. Common Pitfall: Calling the function Immediately

A common newbie mistake is adding () after the function name when assigning it to an event handler.

⛔ INCORRECT (Calls the function immediately upon render):

// React will call handleClick IMMEDIATELY when the component renders. // Result: The function runs at the wrong time, clicks have no effect, or it causes an infinite loop. <button onClick={handleClick()}>Click Me</button>

✅ CORRECT (Passes only the function reference):

// React only calls handleClick WHEN the user clicks. <button onClick={handleClick}>Click Me</button>

✅ CORRECT (Use an Arrow Function if you need to pass parameters):

<button onClick={() => handleDelete(id)}>Delete</button>

2. Event Object & Synthetic Event

When you declare an event handler, React automatically passes an object called the Event Object (often named e or event) as a parameter.

Diagram showing the React Synthetic Event wrapping a native browser event.

2.1. SyntheticBaseEvent

React uses a wrapper class called SyntheticEvent to encapsulate the browser’s native event. This ensures your event handling code behaves identically across all browsers (Cross-browser compatibility).

2.2. Key Properties

  • e.target: The element that triggered the event.
  • e.currentTarget: The element to which the event handler is attached.
  • e.preventDefault(): Prevents the default browser behavior (e.g., stopping a form submission from reloading the page).
  • e.stopPropagation(): Stops the event from bubbling up to parent components.

Form Handling Example:

function LoginForm() { const handleSubmit = (e) => { e.preventDefault(); // 1. Prevents page reload console.log('Form submitted!'); }; return ( <form onSubmit={handleSubmit}> <button type="submit">Login</button> </form>

3. Child-to-Parent Communication

In React, data typically flows in one direction: from Parent down to Child via Props. So, how can a Child component report back to its Parent (e.g., if a user clicks a button in the Child, and the Parent needs to update its state)?

Solution: The Parent component passes a Function (Callback) down to the Child via Props. The Child will then call that function when needed.

Diagram illustrating data flow from child component to parent component.

3.1. The 3-Step Process

  1. Parent: Create a handler function (e.g., handleUpdate).
  2. Parent: Pass that function down to the Child via props (e.g., onUpdate={handleUpdate}).
  3. Child: Call the function from props when an event occurs (e.g., onClick={props.onUpdate}).

3.2. Code Example

Parent Component:

import { useState } from 'react'; import ChildButton from './ChildButton'; export default function Dashboard() { const [count, setCount] = useState(0); // 1. Handler function in the Parent const handleIncrement = () => { setCount(count + 1); }; return ( <div className="p-4 border"> <h1>Dashboard (Parent)</h1> <p>Count: {count}</p> {/* 2. Pass the function down to the Child */} <ChildButton onIncrease={handleIncrement} /> </div> ); }

Child Component:

// Receive onIncrease prop export default function ChildButton({ onIncrease }) { return ( <div className="mt-4 p-2 bg-gray-100 rounded"> <h3>Control Panel (Child)</h3> {/* 3. Call the function on click */} <button onClick={onIncrease} className="bg-blue-500 text-white px-4 py-2 rounded"> Increase Count </button> </div> ); }

4. Hands-on Practice (Labs)

4.1. Lab 1: Instant Search Filter (Mirroring)

Create a search input field and a text list below it.

  • When the user hasn’t typed: Display placeholder text “Start typing something…”.
  • When the user types: The text below should display EXACTLY what’s being typed (Real-time Mirror), but in uppercase.

Screenshot of an input field mirroring text below it in uppercase.

💡 Hint:

  • Use a state variable text to store the input value.
  • The handleChange function receives e: setText(e.target.value).
  • For display, use text.toUpperCase() to transform the data slightly before rendering.

4.2. Lab 2: Background Color Changer (Child -> Parent)

Build a simple background color changer application.

  • ColorDisplay Component (Parent): Features a large square box displaying the current color.
  • ColorControls Component (Child): Contains three buttons (🔴 Red, 🟢 Green, 🔵 Blue).
  • Task: Clicking a button in the Child should change the background color of the box in the Parent.

Screenshot of a color selector application with a large color display and three color buttons.

💡 Hint:

  • In the Parent: Declare a function handleColorChange(newColor).
  • Pass this function down to the Child via a prop: onChangeColor={handleColorChange}.
  • In the Child: Call onClick={() => onChangeColor('red')}. Don’t forget the arrow function to pass parameters!

5. Summary

  1. CamelCase: Always use onClick, onChange, onSubmit, etc.
  2. Function Reference: Use onClick={handleClick}, NOT onClick={handleClick()}.
  3. e.preventDefault(): Always use it when handling form submissions to prevent page reloads.
  4. Callback Props: To pass data back up from Child to Parent, pass a function from the Parent down to the Child, and have the Child call it.

6. Resources

Last updated on