Callback Handlers in JSX — React
Callback Handlers in JSX — React

As we know Props are passed down as information from parent to child components, state can be used to change information over time and to make React show this changed information. However, with those pieces there is no way to pass information up the component tree, since props are naturally only passed downwards. However, we can introduce a callback handler: A callback function gets introduced (A), is used elsewhere (B), but “calls back” to the place it was introduced (C):
import React from "react";
const App = () => {
// A
const handleSearch = (event) => {
// C
console.log(event.target.value);
};
return (
<div>
<h1>My Hacker Stories</h1>
{/* // B */}
<Search onSearch={handleSearch} />
<hr />
</div>
);
};
Now our Search component can use this callback handler from its incoming props to call it whenever a user types into the HTML input field:
const Search = (props) => {
const [searchTerm, setSearchTerm] = React.useState("");
const handleChange = (event) => {
setSearchTerm(event.target.value);
// B
props.onSearch(event);
};
return (
<div>
<label htmlFor="search">Search: </label>
<input
id="search"
type="text"
value={searchTerm}
onChange={handleChange}
/>
</div>
);
};
export default App;
The concept of the callback handler in a nutshell: We pass a function from a parent component (App) to a child component (Search) via props; we call this function in the child component (Search), but have the actual implementation of the called function in the parent component (App).
Essentially when an (event) handler is passed as props from a parent component to its child component, it becomes a callback handler.
React props are always passed down the component tree, and callback handlers passed as functions in props can be used to communicate up the component hierarchy.
Callback Handlers in JSX — React was originally published in Javarevisited on Medium, where people are continuing the conversation by highlighting and responding to this story.
This post first appeared on Read More

