Hello! Let's dive into your next lesson.
Introduction
In our last lesson, we focused on composing components, arranging them into a UI hierarchy like assembling building blocks. We saw how data flows in one direction: from parent to child via props. This is a core principle of React, known as one-way data flow.
But what about the other direction? How does a child component communicate back to its parent? For instance, if you have a custom <Button> component, how does its parent know when it has been clicked? If you have an <Input> component, how does it tell its parent what the user has typed?
This lesson answers that fundamental question. Our learning outcome is to pass functions as props to enable child-to-parent communication. You'll learn how to create a "callback" mechanism that allows child components to send information or signal events back up the component tree. This is the key to making your applications interactive.
The Callback Prop Pattern
In JavaScript, functions are "first-class citizens," meaning they can be treated like any other value: assigned to variables, stored in objects, and, most importantly for us, passed as arguments to other functions.
React leverages this feature for child-to-parent communication. The pattern is simple:
- A parent component defines a function (the "callback").
- The parent passes this function down to a child component as a prop.
- The child component calls this function, which it received via props, whenever a specific event occurs (like a click or an input change).
Because the function was defined in the parent, it executes within the parent's scope, effectively allowing the child to "call up" to its parent.
Let's see a minimal example.
This article from Robin Wieruch's blog provides a very clear, minimal demonstration of the callback pattern. We'll focus on a simple button example that doesn't involve state yet.
Please read the section titled 'Override Component Function with React'. Focus on the two code blocks showing a parent App component passing a handleClick function to a child Button component. Notice how the child can either use the passed-in function or a default one.
As you saw, the parent App defines sayHello, passes it to Button as the handleClick prop, and the Button's native onClick handler calls it. The communication channel is established. This pattern is fundamental to interactivity in React.
Typing Function Props in TypeScript
Given your proficiency in TypeScript, you know that correctly typing function signatures is crucial for robust code. When passing functions as props, we need to define the types for their parameters and return value.
A common convention for props that are event handlers is to name them starting with "on", like onClick, onChange, or onSubmit.
// Parent Component
const App = () => {
const handleItemSelect = (id: string) => {
console.log(`Item with id: ${id} was selected.`);
};
return <ChildComponent onItemSelect={handleItemSelect} />;
};
// Child Component
type ChildProps = {
// The function expects a 'string' and returns nothing ('void')
onItemSelect: (id:string) => void;
};
const ChildComponent = ({ onItemSelect }: ChildProps) => {
return (
<button onClick={() => onItemSelect('item-123')}>
Select Item
</button>
);
};
Here, the ChildProps type clearly documents that onItemSelect must be a function that accepts a single string argument. This prevents bugs and makes the component's API self-documenting.
The following guide offers a comprehensive look at typing various kinds of function props.
Complete Guide to React Component Props with TypeScript
This guide from Steve Kinney provides an excellent reference for typing function props in TypeScript. It covers several common scenarios you will encounter.
Read the section titled 'Function Props: Callbacks and Event Handlers'. Pay close attention to the SearchProps interface. It demonstrates how to type simple callbacks, async functions, functions with multiple parameters, and optional callbacks that receive a React event object.
Handling DOM Events
The most frequent use case for function props is handling native DOM events from within your custom components. A parent might need to react when a child's <button> is clicked or an <input> value changes.
React provides its own event types that are compatible across different browsers. When typing your event handler props, you'll use these types to get full IntelliSense and type safety for the event object.
This video from Codevolution provides a concise and practical guide to typing these handlers.
React TypeScript Tutorial - 6 - Event Props
Let's watch how to correctly type the two most common event handlers: onClick and onChange.
Please watch the entire video (00:00:30 - 00:07:01). It is divided into two parts: Click Events (00:00:30 - 00:04:25): Notice the type React.MouseEvent. The video shows how to handle a simple click, a click where you need the event object, and a click where you also pass a custom argument like an ID. Change Events (00:04:25 - 00:07:01): Here, focus on the React.ChangeEvent type. For now, ignore the value prop on the input; we're only interested in how the handleChange function is defined, typed, and passed as a prop. We will connect this to state in the next module.
The key takeaways from the video are the specific TypeScript types for React events:
- For mouse events (like clicks):
React.MouseEvent<T>, whereTis the element type (e.g.,HTMLButtonElement). - For change events (like on an input):
React.ChangeEvent<T>, whereTis the element type (e.g.,HTMLInputElement).
Using these types ensures you can safely access properties like event.target.value without TypeScript complaining.
Visualizing the Data Flow
This entire process enables a controlled and predictable data flow in your application. Let's visualize it. The following diagram illustrates a pattern called "lifting state up," which we will cover in detail in the next module. However, the first two steps of the diagram perfectly depict the child-to-parent communication we've just learned.

- Step 1: The parent component (
Component A) defines a handler function and passes it down toComponent Bas a prop. - Step 2: An event occurs in
Component B(e.g., a user click).Component Binvokes the function it received as a prop, passing any relevant data (e.g., an ID, or the event object itself) back up as an argument.
The subsequent steps, which involve updating state and passing new data down to other children (Component C and D), are what we will explore next. For today, mastering steps 1 and 2 is the goal.
Test your understanding!
You are building a settings panel. You have a SettingsPanel parent component and a ThemeSwitcher child component.
The ThemeSwitcher component should contain a button that says "Toggle Dark Mode". When this button is clicked, it should notify the parent.
Your task:
- Define the TypeScript props interface for
ThemeSwitcher. It should accept one prop,onThemeToggle, which is a function that takes no arguments and returns nothing. - Implement the
ThemeSwitchercomponent. - Show how the
SettingsPanelparent component would define a handler function (handleThemeToggle) and render theThemeSwitcher, passing the handler to it. ThehandleThemeTogglefunction should simply log "Theme toggled!" to the console.
Show answer
Here is a possible solution:
1. & 2. ThemeSwitcher Component Implementation
// ThemeSwitcher.tsx
import React from 'react';
// 1. Define the props interface
type ThemeSwitcherProps = {
onThemeToggle: () => void;
};
// 2. Implement the component
export const ThemeSwitcher = ({ onThemeToggle }: ThemeSwitcherProps) => {
return (
<button onClick={onThemeToggle}>
Toggle Dark Mode
</button>
);
};
3. SettingsPanel Parent Component Implementation
// SettingsPanel.tsx
import React from 'react';
import { ThemeSwitcher } from './ThemeSwitcher';
export const SettingsPanel = () => {
// Define the handler function in the parent
const handleThemeToggle = () => {
console.log("Theme toggled!");
};
return (
<div>
<h2>Settings</h2>
<ThemeSwitcher onThemeToggle={handleThemeToggle} />
</div>
);
};
This demonstrates the complete pattern: the SettingsPanel owns the logic (handleThemeToggle) and passes it down to the ThemeSwitcher, which is only responsible for rendering the button and calling the function when clicked.
Conclusion
Today, you've learned one of the most crucial patterns in React for building interactive applications. By combining one-way data flow (props) with the first-class nature of JavaScript functions, we can create a clear and robust system for components to communicate.
Key Takeaways:
- Child-to-parent communication is achieved by passing functions as props. The parent defines a function and gives it to the child, and the child calls that function to "phone home."
- This pattern is often called the callback handler pattern.
- TypeScript provides strong typing for function props, allowing you to define the exact signature (parameters and return type) for an event handler, improving code safety and documentation.
- React has its own synthetic event types (e.g.,
React.MouseEvent,React.ChangeEvent) that you should use when typing handlers for native DOM events.
Next Steps
We've successfully established the communication channel. The parent can now listen to the child. But what should the parent do with that information? In our ThemeSwitcher example, logging to the console isn't very useful. The parent needs to remember that the theme has changed and re-render the UI accordingly.
In our next module, we will begin our journey into managing state. You'll be introduced to the useState hook, which allows components to remember information and trigger re-renders when that information changes. We will see how the callback pattern we learned today is the essential glue that connects child component events to parent component state updates.