Handlers as Props
A handler as a prop is a function passed from a parent to a child. The child calls the function when an event happens.
The child calls the prop
ChildButton calls props.onPress when the button is clicked.
function ChildButton(props) {
return <button onClick={props.onPress}>Press</button>;
}The parent defines the handler
The parent owns the code that runs on the click.
function handlePress() {
console.log('Pressed');
}The parent passes the handler
App passes handlePress down as the onPress prop.
<ChildButton onPress={handlePress} />Example
function handlePress() {
console.log('Pressed');
}
function ChildButton(props) {
return <button onClick={props.onPress}>Press</button>;
}
export default function App() {
return <ChildButton onPress={handlePress} />;
}Key points
- A function is a value, so it can pass as a prop.
- The parent defines the handler.
- The child receives the handler through props.
- The child attaches the handler to an event.
- The parent code runs when the child event fires.
In this example, handlePress logs Pressed to the console. ChildButton takes props and returns a button. The button uses props.onPress as its click handler. App renders ChildButton and passes handlePress as onPress. A click runs handlePress. The console shows Pressed.
Note
The child does not need to know what the handler does.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Where does the handler code live when a handler passes as a prop?