bsky
bsky

Reputation: 20222

React re-render component when another component is changed

I have two React source files, A and B. A, in its render method, calls B like this:

{this.state.classificationSelected
      ?
      <div>
      <B classification={this.props.categories[this.state.categoryIndex].classes[this.state.classificationIndex]} ref="B"/>
      </div>
      :
      null
    }

So B is rendered if the Classification component of A is selected.

In B, I have the following method which computes some values based on A's Classification:

getSingleChoiceAttributes: function() {
    var singleChoiceAttributes = [];
    for(let attribute of this.props.classification.attributes){
        if(attribute.attributeType == 'SingleChoice') {
            singleChoiceAttributes.push(attribute);
        }
    }
    return singleChoiceAttributes;
},

Currently, I am calling this method from B's ComponentWillMount method.

I would like this method to get executed every time A's classification is changed. However, for now it is called only when A's classification is first selected.

How can I make the getSingleChoiceAttributes method change every time A's Classification(represented by this.state.classificationIndex) is changed?

Upvotes: 2

Views: 2471

Answers (1)

Kyeotic
Kyeotic

Reputation: 19847

Use componentWillReceiveProps.

void componentWillReceiveProps(
  object nextProps
)

Invoked when a component is receiving new props. This method is not called for the initial render.

Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState(). The old props can be accessed via this.props. Calling this.setState() within this function will not trigger an additional render.

Upvotes: 2

Related Questions