Bird
Raised Fist0
React Nativemobile~20 mins

Callback props in React Native - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Counter Screen
A simple screen with a counter display and a button. Pressing the button increases the counter using a callback prop passed to the button component.
Target UI
Counter Screen

  Count: 0

  [ Increase ]
Display a number starting at 0
Create a Button component that accepts a callback prop named onPress
When the button is pressed, the counter increments by 1
Use the callback prop to notify the parent component about the button press
Starter Code
React Native
import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';

function CounterButton(props) {
  // TODO: Use props.onPress as the button press handler
  return (
    <TouchableOpacity style={styles.button} onPress={() => { /* TODO */ }}>
      <Text style={styles.buttonText}>Increase</Text>
    </TouchableOpacity>
  );
}

export default function CounterScreen() {
  const [count, setCount] = useState(0);

  // TODO: Define a function to handle button press and update count

  return (
    <View style={styles.container}>
      <Text style={styles.countText}>Count: {count}</Text>
      {/* TODO: Render CounterButton and pass the callback prop */}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  countText: { fontSize: 32, marginBottom: 20 },
  button: { backgroundColor: '#007AFF', paddingVertical: 12, paddingHorizontal: 24, borderRadius: 8 },
  buttonText: { color: 'white', fontSize: 18 }
});
Task 1
Task 2
Task 3
Solution
React Native
import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';

function CounterButton(props) {
  return (
    <TouchableOpacity style={styles.button} onPress={props.onPress} accessibilityLabel="Increase counter button">
      <Text style={styles.buttonText}>Increase</Text>
    </TouchableOpacity>
  );
}

export default function CounterScreen() {
  const [count, setCount] = useState(0);

  function handleIncrease() {
    setCount(prevCount => prevCount + 1);
  }

  return (
    <View style={styles.container}>
      <Text style={styles.countText} accessibilityLiveRegion="polite">Count: {count}</Text>
      <CounterButton onPress={handleIncrease} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff' },
  countText: { fontSize: 32, marginBottom: 20, color: '#000' },
  button: { backgroundColor: '#007AFF', paddingVertical: 12, paddingHorizontal: 24, borderRadius: 8 },
  buttonText: { color: 'white', fontSize: 18 }
});

We created a CounterButton component that accepts an onPress callback prop. This prop is used as the handler for the button press event.

In the CounterScreen component, we keep track of the count state using useState. We define a function handleIncrease that increments the count.

This function is passed down to CounterButton as the onPress prop. When the button is pressed, it calls this function, updating the count in the parent.

We also added accessibility labels to improve usability for screen readers.

Final Result
Completed Screen
Counter Screen

  Count: 1

  [ Increase ]
User taps the 'Increase' button
The number shown after 'Count:' increases by 1 each tap
Stretch Goal
Add a 'Decrease' button that decreases the count using a callback prop
💡 Hint
Create another button component or reuse CounterButton with a different onPress prop that subtracts 1 from count

Practice

(1/5)
1. What is the main purpose of using callback props in React Native components?
easy
A. To manage component state internally
B. To style components dynamically
C. To allow child components to communicate events back to parent components
D. To fetch data from an API

Solution

  1. Step 1: Understand callback props role

    Callback props are functions passed from parent to child to notify the parent about events.
  2. Step 2: Identify communication direction

    They let children send information or events back to parents, enabling communication.
  3. Final Answer:

    To allow child components to communicate events back to parent components -> Option C
  4. Quick Check:

    Callback props = child-to-parent communication [OK]
Hint: Callback props let children tell parents about events [OK]
Common Mistakes:
  • Thinking callback props manage styling
  • Confusing callback props with state management
  • Assuming callback props fetch data
2. Which of the following is the correct way to pass a callback prop named onPress from a parent to a child component in React Native?
easy
A.
B.
C. handlePress />
D.

Solution

  1. Step 1: Recall JSX prop syntax

    Props are passed as attributes with values inside curly braces for functions.
  2. Step 2: Match correct syntax

    uses onPress={handlePress}, which is valid JSX syntax.
  3. Final Answer:

    <ChildComponent onPress={handlePress} /> -> Option A
  4. Quick Check:

    JSX props use = and curly braces for functions [OK]
Hint: Use = and curly braces to pass functions as props [OK]
Common Mistakes:
  • Using colon : instead of =
  • Using arrow => inside prop
  • Adding parentheses () in prop name
3. Given the code below, what will be logged when the button is pressed?
function Parent() {
  const handleClick = () => console.log('Clicked!');
  return <Child onPress={handleClick} />;
}

function Child({ onPress }) {
  return <Button title="Press me" onPress={onPress} />;
}
medium
A. Nothing happens
B. Clicked!
C. Error: onPress is not a function
D. Button title is logged

Solution

  1. Step 1: Trace callback prop usage

    The Parent passes handleClick as onPress prop to Child.
  2. Step 2: Check Child button onPress

    The Child uses onPress prop as the button's onPress handler, so pressing calls handleClick.
  3. Final Answer:

    Clicked! -> Option B
  4. Quick Check:

    Button press triggers parent's callback [OK]
Hint: Child calls parent's function on event [OK]
Common Mistakes:
  • Assuming onPress is undefined
  • Thinking button title logs
  • Ignoring callback function call
4. Identify the error in this React Native code snippet:
function Parent() {
  const handlePress = () => alert('Pressed');
  return <Child onPress={handlePress()} />;
}

function Child({ onPress }) {
  return <Button title="Click" onPress={onPress} />;
}
medium
A. alert cannot be used in React Native
B. Child component is missing props destructuring
C. Button component does not support onPress
D. handlePress is called immediately instead of passed as a function

Solution

  1. Step 1: Analyze prop passing

    In onPress={handlePress()}, the function is called immediately, passing its result (undefined) instead of the function.
  2. Step 2: Understand correct usage

    We should pass the function itself without calling it: onPress={handlePress}.
  3. Final Answer:

    handlePress is called immediately instead of passed as a function -> Option D
  4. Quick Check:

    Pass function reference, not call it [OK]
Hint: Pass function, don't call it when passing as prop [OK]
Common Mistakes:
  • Calling function instead of passing reference
  • Thinking alert is invalid in React Native
  • Ignoring destructuring in Child
5. You want a child component to notify the parent when a text input changes, but only if the input length is more than 3 characters. How should you implement the callback prop pattern to achieve this?
hard
A. Pass a callback prop from parent; child calls it only when input length > 3
B. Child manages input state and updates parent state directly
C. Parent listens to child's internal state without callback
D. Use a global variable to share input value between components

Solution

  1. Step 1: Understand callback prop usage for conditional events

    The parent passes a function as a prop to the child to receive input changes.
  2. Step 2: Implement conditional call in child

    The child calls the callback only if the input length is more than 3, controlling when to notify the parent.
  3. Final Answer:

    Pass a callback prop from parent; child calls it only when input length > 3 -> Option A
  4. Quick Check:

    Child controls event call; parent receives updates [OK]
Hint: Child calls parent callback only when condition meets [OK]
Common Mistakes:
  • Letting child update parent state directly
  • Ignoring conditional logic in child
  • Using global variables for communication
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard