ORStudios
ORStudios

Reputation: 3233

Update state values with props change in reactjs

I have a modal component that should be called when setState changes but for some reason it is not updating. In the first file Im setting the following in render.

<ModalParcel showModal={this.state.showModal} parcelToConfirm={this.state.dataForParcelToConfirm} />

Within the Modal component constructor() I am setting the following.

constructor(props) {
    super(props);

    console.log("Constructor for modal componenet called.")

    //this.renderRowForMain = this.renderRowForMain.bind(this);

    this.state = {
      show: this.props.showModal
    };

  }

render() {

    if(this.state.show == true){

        var content = 
        <View style={styles.modal}>
            <View style={styles.modalContent}>
                <TouchableHighlight onPress={() => this.closeModal()}>
                    <Text>Close</Text>
                </TouchableHighlight>
            </View>
        </View>;

    }else {

        var content = null;

    }

    return ( content );

  }

The problem is that the constructor() only gets called once on initial creation. I was under the impression that when I update the state to show the modal the constructor would be called again but this isn't happening.

I basically want to change the state to show the modal and then re-run render().

Upvotes: 4

Views: 2922

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104529

No constructor will not get called when component re-rendered, it will get called only on initial rendering.

I think, there are two ways by which you can solve your issue:

1. Use componentWillReceiveProps(){ lifecycle method it will get called whenever any change happens to props values, so you can update the Modal component state value showModal here, like this:

componentWillReceiveProps(nextProp){
   this.setState({
      show: nextProps.showModal
   });
}

As per DOC:

componentWillReceiveProps() is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.

2. Don't store the props value in state variable and directly use this.props.showModel in Model component, by this way whenever any change happens to props values, Modal component will take the updated values.

Upvotes: 5

Related Questions