javascript / beginner
Snippet
Passing Callback Functions via Child Component Props
Passing callback functions down to child components via props enables upward data and event flow in React. The child triggers the function passed by the parent when a DOM event occurs.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import React, { useState } from 'react';function ActionButton({ onCustomClick, label }) {return <button onClick={onCustomClick}>{label}</button>;}function ParentContainer() {const [count, setCount] = useState(0);const handleIncrement = () => {setCount(prev => prev + 1);};return (<div><p>Total Clicks: {count}</p><ActionButton onCustomClick={handleIncrement} label="Add Count" /></div>);}export default ParentContainer;
react
Breakdown
1
function ActionButton({ onCustomClick, label }) {
Defines a reusable child component that receives a handler function 'onCustomClick' and a text 'label' as props.
2
const handleIncrement = () => { setCount(prev => prev + 1); };
Defines the event callback function in the parent that increments state.
3
<ActionButton onCustomClick={handleIncrement} label="Add Count" />
Passes the parent's function reference into the child component's prop.