raph
raph

Reputation: 319

Passing props into state in React Native?

I have a button on the homescreen which toggles the text in the AlertBar.

So when I press a Button, the text in AlertBar should change according to the state isParked. Currently when I press the button, nothing happens... and I'm unsure why.

Here's my homescreen:

class Home extends Component {

    constructor(props) {
      super(props);
      this.state = {
          isParked: false
      };    
  }


    pressPark = () => this.setState({isParked:true})

    render() {
        console.ignoredYellowBox = ['Remote debugger'];

        return (

            <View>
                    <View>
                        <AlertBar isParked={this.state.isParked}/>
                    </View>

                    <View style={styles.parkButton}>
                        <Button title='PARK' onPress={this.pressPark} color='green'/>
                    </View>
            </View>

            );
        }
    }

Here's my AlertBar.js:

class AlertBar extends Component {

        state = {
            region: 'Singapore',
            isParked: this.props.isParked,
            alertText: null
    }


...   some unrelated code ...

    componentDidMount() {

        if (this.state.isParked === false) {
                this.setState({alertText: "You're parking at"})} else if (this.state.isParked === true) {
                this.setState({alertText: "You're parked at"})}

        alert(this.state.alertText)
            }

    componentWillUnmount() {
        // some unrelated code
    }

    render() {

... some unrelated code...

        return(

                <View style={styles.container}>
                    <Text style={styles.welcomeText}>
                        {this.state.alertText}
                    </Text>
                    <Text style={styles.locationText}>
                        {this.state.region}
                    </Text>
                </View>
            )
    }
}

Am I doing this wrong? I can't tell what's wrong.... Please help! Thanks!

Upvotes: 1

Views: 705

Answers (2)

plahstic
plahstic

Reputation: 1621

At this point, your AlertBar component is not handling any prop changes.

What you'll need to do, is map your props to the state whenever an update is received.

Add this line of code in your AlertBar.js and it will map isParked to state whenever it receives an update.

componentWillReceiveProps(props) {
    this.setState({ isParked: props.isParked });
}

Upvotes: 0

Ji aSH
Ji aSH

Reputation: 3457

Use

if (this.props.isParked === false)

Instead of

if (this.state.isParked === false)

(and dont transfer props to state directly, this make no sense anyway :))

Upvotes: 2

Related Questions