javascript / beginner
Snippet
Passing Event Handler Callbacks to Child Components
In React, parent components pass functions down to child components via props. This allows child components to communicate events back up to the parent without needing to know or manage parent state directly.
snippet.js
javascript
1
2
3
4
5
6
7
8
function ActionButton({ onTrigger, label }) {return <button onClick={onTrigger}>{label}</button>;}function Dashboard() {const notifyUser = () => console.log('Action triggered!');return <ActionButton onTrigger={notifyUser} label="Confirm" />;}
react
Breakdown
1
function ActionButton({ onTrigger, label }) {
Defines a presentational child component that unpacks a callback function and label string from props.
2
return <button onClick={onTrigger}>{label}</button>;
Attaches the passed callback function directly to the native button's onClick event.
3
const notifyUser = () => console.log('Action triggered!');
Creates an event handler function inside the parent component.
4
return <ActionButton onTrigger={notifyUser} label="Confirm" />;
Renders the child component while passing the handler function reference through the onTrigger prop.