Callback props let a parent component talk to a child component by sending a function. This helps the child tell the parent when something happens.
0
0
Callback props in React Native
Introduction
When a button inside a child component needs to tell the parent it was pressed.
When a form inside a child component wants to send data back to the parent.
When you want to keep the parent in control but let the child trigger actions.
When you want to reuse a child component but handle events differently in each parent.
Syntax
React Native
function Parent() {
function handleEvent() {
// do something
}
return <Child onEvent={handleEvent} />;
}
function Child({ onEvent }) {
return <Button onPress={onEvent} title="Click me" />;
}The parent sends a function as a prop to the child.
The child calls this function when needed, like on a button press.
Examples
The child button calls the parent's sayHello function when pressed.
React Native
function Parent() {
function sayHello() {
alert('Hello from parent!');
}
return <Child onPress={sayHello} />;
}
function Child({ onPress }) {
return <Button onPress={onPress} title="Greet" />;
}The child sends a message string back to the parent when the button is pressed.
React Native
function Parent() {
function logMessage(message) {
console.log('Message:', message);
}
return <Child onSend={logMessage} />;
}
function Child({ onSend }) {
return <Button onPress={() => onSend('Hi!')} title="Send" />;
}Sample App
This app shows a number and a button. When you press the button, the number goes up by one. The child button tells the parent to update the number using a callback prop.
React Native
import React from 'react'; import { View, Button, Text } from 'react-native'; export default function Parent() { const [count, setCount] = React.useState(0); function handleIncrement() { setCount(prevCount => prevCount + 1); } return ( <View style={{ padding: 20 }}> <Text>Count: {count}</Text> <Child onIncrement={handleIncrement} /> </View> ); } function Child({ onIncrement }) { return <Button title="Add 1" onPress={onIncrement} />; }
OutputSuccess
Important Notes
Always name callback props starting with 'on' to show they are event handlers.
Use arrow functions in the child if you need to pass arguments to the callback.
Callback props keep your components reusable and easy to manage.
Summary
Callback props let children tell parents about events.
Parents send functions as props; children call them when needed.
This pattern helps keep components simple and communication clear.