Shashika Virajh
Shashika Virajh

Reputation: 9457

How to pass a prop to match up with a state property in child in react-native

In my application, I created a timer component. This is a smart component because I wanted to handle the counter state inside the component.

this is my code

import React, { Component } from "react";

import {
  View,
  Text,
  StyleSheet
} from "react-native";


import { RoundedButton} from "../../mixing/UI"; 


class Timer extends Component {
    constructor(props) {
        super(props);

        this.state = {
            counter: 30
        }

        this.interval = null;
    }

    componentWillUnmount() {
        cleanUp();
    }

    cleanUp = () => {
        clearInterval(this.interval);
    }

    decreaseCounter = () => {
        if (this.state.counter === 0) {
            return this.cleanUp();
        }

        this.setState({counter: this.state.counter - 1});
    }

    startCounter = () => {
        this.interval = setInterval(this.decreaseCounter, 1000);
    }

    render() {
        return (
            <View>
                <RoundedButton  text='Log in' onPress={() => this.startCounter()} />
                    <Text>{this.state.counter}</Text>
                <RoundedButton  text='Log in' onPress={() => this.cleanUp()} />
            </View>
        );
    }


}


// styles
const styles = StyleSheet.create({

});

export default Timer;

Now I want to call this from my parent screen. If I pass the counter as a prop,

Now the counter state can't be handled from Timer component. How can I handle the state of the child based on the parent prop.

Upvotes: 0

Views: 54

Answers (1)

Amila Dulanjana
Amila Dulanjana

Reputation: 1914

you can use react component lifecycle componentDidMount()

componentDidMount(){ this.setState({counter: this.props.counter}); }

There after you can use this.setState({counter: this.state.counter - 1})

Upvotes: 1

Related Questions