Callback Handlers in JSX
Explore how to create and use callback handlers in JSX to manage user interactions in React. This lesson explains passing functions as props to communicate between components, enabling event handling that updates parent components from child components.
We'll cover the following...
We’ll focus on the input field and label, by separating a standalone Search component and creating an instance of it in the App component. Through this process, the Search component becomes a sibling of the List component, and vice versa. We’ll also move the handler and the state into the Search component to keep our functionality intact.
Handling user interactions like this is a fundamental part of managing events in React.
We have an extracted Search component that handles state and shows state without revealing its content. The component displays the searchTerm as text but doesn’t share this information with its parent or sibling components yet. Since Search component does nothing except show the search term, it becomes useless for the other components.
There is no way to pass information as JavaScript data types up the component tree, since props are naturally only passed downwards. However, we can introduce a callback handler as a function. This is a common pattern for managing various events in React, such as when a user types in a field or when you use onClick in React to handle button presses.
-
A callback function gets introduced (A),
-
is used elsewhere (B),
-
It “calls back” to the place it was introduced (C).
Use comments in your source code to omit A, B, and C, as these are reminders which task each block of code is to perform.
Consider the concept of the callback handler: We pass a function from one component (App) to another component (Search); we use it in the second component (Search); but use the actual callback of the function call in the first component (App).
This way, we can communicate up the component tree. A handler function used in one component becomes a callback handler, which is passed down to components via React props. While standard attributes like onClick handle local element events, callback handlers allow those events to trigger changes high up in your application hierarchy.
React props are always passed down as information to the component tree, and callback handlers passed as functions in props can be used to communicate up the component hierarchy.
Let’s visualize this in the code below: