0

I am working with React Native now, and I want to determine conditions inside of the setState. After that operation I want to give that value to another class and change the text inside of the that class.

Firstly, I want to determine and change the isLightOn value between true and false when I press to button.

Here is my codes:


class LightButton extends  Component {

    state = {
        isLightOn: false
    }

    render() {
        return(
            <View style={styles.red} >

                <LightBulb> </LightBulb>
          <Button
           title="Turn light on"
           onPress={() => { this.setState({isLightOn:true}) }}
          />
            </View>

        );
    }
} 

After that, I want to use that isLightOn value inside of the another class. According to that value there will some text changes off to on or on to off.

Here is my second class:

class LightBulb extends Component {
    render() {
        return (

            <View style={styles.green} >

                <Text> OFF </Text>

            </View>

        );
    }
}

How to change data with using setState() and pass thah data to another class?

1

1 Answer 1

1

For your isLightOn state value use the following expression when the button is pressed: this.setState({isLightOn: !this.state.isLightOn})

Then you need to pass the state to your LightBulb component.

In the end you should conditionally render your component:

class LightButton extends  Component {

    state = {
        isLightOn: false
    }

    render() {
        return(
            <View style={styles.red} >

                <LightBulb isLightOn={this.state.isLightOn}> </LightBulb>
          <Button
           title="Turn light on"
           onPress={() => { this.setState({isLightOn: !isLightOn}) }}
          />
            </View>

        );
    }
} 
class LightBulb extends Component {
    render() {
        return (

            <View style={this.props.isLightOn ? styles.green : styles.red} >

                {this.props.isLightOn 
                  ?
                    <Text> OFF </Text>
                  :
                    <Text> ON </Text>
                }

            </View>

        );
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.