Passing data from a React Native component to its parent component that invoked it

Currently, I am developing a react native application that incorporates a timer component which I have created with the following code:

import React, { Component } from 'react';
import {
    Platform,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';
import styles from '../styles/style';

export default class Timer extends Component<{}> {
    constructor(props) {
        super();
        this.state = {
            time: 10,
            timerStarted: false
        }
    }

    startTimer() {
        this.interval = setInterval(() => {
            this.setState({
                isFirstRender: !this.state.isFirstRender,
                time: this.state.time-1,
                isTimerRunning: true
            });
        }, 1000);
    }

    render() {
        if (!this.state.isTimerRunning)
            this.startTimer();

        return (
            <View style={styles.scoreBoard}>
                <Text style={styles.timerText}>Time: {this.state.time}</Text>
            </View>
        );
    }
}

In this component, there is a state variable called time that decreases from 10 in intervals of one second. In order to alert the calling component when the timer reaches zero, I need to implement a notification system. The primary JavaScript file in my program is App.js, which instantiates the timer within its render function as shown below:

render () {

        return (
            <View style={{flex: 1, flexDirection: 'row'}}>
                <View style={{flex: 1}}>
                    {/*This below is the component I need to return a value to this main class we are in*/}
                    <MyTimer />
                </View>
            </View>
        );
    }

I aim for the Timer class to send back some data, potentially a boolean, to notify the main class when the countdown ends. One approach could be passing a member function from the main class to the Timer class as a prop, although I am unsure if this method is correct. I have experimented with different strategies but leveraging props to transmit information to a component is straightforward, yet retrieving data proves to be challenging. Any guidance on achieving this would be appreciated. Thank you.

Answer №1

Passing a function from the parent component to the child component allows you to update the parent by invoking the function in the child:

onTimerEnd = () => //do something in parent

render () {

        return (
            <View style={{flex: 1, flexDirection: 'row'}}>
                <View style={{flex: 1}}>
                    {/*This below is the component I need to return a value to this main class we are in*/}
                    <MyTimer onTimerEnd={this.onTimerEnd} />
                </View>
            </View>
        );
    }

It's recommended to start the timer in the constructor rather than in the render method, as render will be called each time the component re-renders:

export default class Timer extends Component<{}> {
    constructor(props) {
        super();
        this.state = {
            time: 10,
        }
        this.startTimer(); //start timer
    }

    startTimer() {
        localTime = this.state.time;
        this.interval = setInterval(() => {
            this.setState({
                time: this.state.time-1,
            }, () => {
                if (this.state.time === 0) this.props.onTimerEnd() //invoke when timer hits 0
            });
        }, 1000);
    }

    render() {   
        return (
            <View style={styles.scoreBoard}>
                <Text style={styles.timerText}>Time: {this.state.time}</Text>
            </View>
        );
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The node sends a request to the API to retrieve data, which is then stored in an array. Subsequently, another request is

var UfcAPI = require('ufc-api'); var ufc = new UfcAPI({ version: '3' }); const fighterIdList = []; function fetchFighterIds() { ufc.fighters(function(err, res) { for (let i = 0; i < res.body.length; i++) { ...

What is the best way to transfer values from a function component to a class component in App.js?

How can longitude and latitude values be passed from the function component Demo.js to the class component App.js, where App.js is the Parent Component and Demo.js is the Child Component? Reference files: import React from 'react'; import PropT ...

What is the best way to eliminate a particular item from an array that is nested within the object? (using methods like pop() or any

I am struggling to remove the 'hello5' from the years in myObj. Although I tried using the 'pop' prototype, an error occurred in the browser console displaying: 'Uncaught TypeError: Cannot read property 'type' of undefi ...

How to Retrieve URL Parameters in Gatsby

As I delve into learning React and Gatsby, I encountered an issue with my page containing URL parameters. Despite everything working smoothly on my local machine, after the gatsby build process, the variable url = undefined. How can I retrieve these para ...

Implementing bcryptjs with NodeJS using ES6

Having trouble incorporating the bcryptjs package into my React project. Currently encountering the following error: Could not find a declaration file for module 'bcryptjs'. ‘…/node_modules/bcryptjs/index.js' implicitly has an 'any ...

Dynamic HTML Rendering based on ASP.NET Web.config Key

I need to control the visibility of certain markup based on a key in the web.config file. The key is defined as follows: <add key="IsDemo" value ="true"/> I am looking for a way to show or hide the markup for a non-server HTML element without using ...

Capture multiple photos and videos from the camera using iOS Monotouch UIImagePickerController

We're currently encountering a peculiar issue with a UIImagePickerController in our app. Users can fill out forms and attach images/videos within these forms. They have the option to add multiple media files from the camera roll or capture new ones wh ...

Simple code for form with email confirmation

I'm looking to create a simple form for my website that sends an email notification. The current code I have doesn't automatically send the email notification. Can anyone help me with adding this feature? <!DOCTYPE html> <html> <b ...

Where is the response coming from within res.json()?

I am currently exploring the routing section and attempting to unravel the functionality within this code snippet, particularly with regards to res.json. router.get('/', function(req, res){ db.find() .then(function(todos){ res.json(todos ...

How to obtain mouse coordinates on a texture using three.js

I am looking to develop an engaging interactive panorama similar to the one showcased here: However, I am interested in allowing users to have the ability to interact with it. Is it feasible to retrieve coordinates from the texture based on mouse movemen ...

The In-App Purchase section is nowhere to be found on iTunes Connect

My app was in the prepare for submission phase with included in-app purchase items. I linked them to my app and submitted it for review last week, but unfortunately, a developer rejected it over the weekend. Now, as I try to resubmit the updated build, I ...

What is the best way to delete a jQuery.bind event handler that has been created for an event

I have a div and I need to assign two scroll functions to it, but I also want to remove one of them after a certain condition is met. <div id="div1" class="mydivs"> something </div> <div id="div2">Some crap here</div> <script&g ...

Dealing with asynchronous requests in Axios: A guide to solving the challenge

I'm working on a page named _id.vue in my Nuxt.js project: <template> <div class="wrapper"> <HeaderApp> <DivHeaderMenu> </DivHeaderMenu> </HeaderApp> <CenterContentDinamicFirmeni ...

There was an issue with the Discord.js (v12) Giveaway Command that resulted in an error stating "Error: Cannot read property 'hasPermission' of undefined"

Hey everyone, I'm trying to develop my own Discord bot and I want to add a giveaway command to it. I found an example code online that I tried to implement, but unfortunately, it's not working as expected... const ms = require('ms'); c ...

How can CSS and JavaScript be used to strategically position two upright images next to each other within a dynamically resizing container?

Looking for a way to display two portrait images side by side within a flexible container with 100% width? The challenge I'm facing is accommodating varying widths of the images while ensuring they are the same height. <div class="container"> ...

What could be the reason for my array being nested inside another array as a value in a dictionary

I am having some difficulty understanding how the selected array is being returned in my dictionary. Could you please provide me with an explanation? The language being used is javascript. I have constructed a dictionary with arrays as values. However, wh ...

Fixed position is used on elements that should always remain in the exact

I have a fixed menu on my website that is working perfectly fine. I also have a container (not using Bootstrap) that should stay fixed when it reaches the static menu. Everything is functioning as expected, except when I resize the window, the container se ...

Are $.ajax() callback functions not tied to the requests they originate from?

The code is quite intricate, so I have simplified it below in order to verify whether the behavior I am encountering is normal or if there is some other error I have introduced into the code. I have two distinct ajax requests, each with its own unique cal ...

What is the best way to navigate from one div to a particular slide within a slider?

Let's say I have two web pages: index.html and page.html. On page.html, there is a slider with 9 slides created using the plugin StackSlider. Now, when a link on index.html is clicked, I want to navigate to a specific slide, like slide number 4, on pa ...

Display HTML instead of text in print mode

Hello, I need help with printing HTML code, specifically an iframe. When I try to add my HTML iframe code, it only prints as plain text. I want to be able to see the actual iframe with its content displayed. Thank you. <script> const messages = [&apo ...