bsky
bsky

Reputation: 20242

React - change state when props are changed

I have a React component, AttributeSingleChoice which I am calling like this:

Based on the new props I receive in it, I want to change its state, like this:

componentWillReceiveProps: function() {
    var attributeTypes = this.selectAttributes();
    this.setState({
        singleChoiceAttributes: attributeTypes});
},

selectAttributes: function() {
    return this.props.classification.attributes.map(function (elem) {
        if(elem.attributeType == "A") {
            return {description: elem.description, name: elem.name}
        }
    }).filter(Boolean);
},

However, if I use componentWillReceiveProps, state.props will remember the old props, not the new ones, as I would like.

I tried using componentWillUpdate instead but I can't set the state inside componentWillUpdate.

How can I change the state of the component based upon new props?

Upvotes: 2

Views: 461

Answers (3)

Dan Prince
Dan Prince

Reputation: 30009

The componentWillReceiveProps hook is passed the new props as an argument.

componentWillReceiveProps: function(newProps) {
  newProps !== this.props
}

You can accept an alternate props with a parameter on your selectAttributes function.

selectAttributes: function(props) {
  // fallback to regular props if nothing passed
  props = props || this.props;

  return props.classification.attributes.map(function (elem) {
    // ...
  }).filter(Boolean);
}

Then pass the new props when they are available.

componentWillReceiveProps: function(newProps) {
  var attributeTypes = this.selectAttributes(newProps);

  this.setState({
    singleChoiceAttributes: attributeTypes
  });
}

Upvotes: 4

molson504x
molson504x

Reputation: 1200

Your componentwillrecieveprops header is incorrect. You should take in a parameter for nextProps, which will contain the props being passed in. Then set your state variable based off of the nextProps. http://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops

Upvotes: 1

TbWill4321
TbWill4321

Reputation: 8676

You need to pass nextProps in to your function:

componentWillReceiveProps: function( nextProps ) {
    var attributeTypes = this.selectAttributes( nextProps );
    this.setState({
        singleChoiceAttributes: attributeTypes});
},

selectAttributes: function( nextProps ) {
    var props = nextProps || this.props;
    return props.classification.attributes.map(function (elem) {
        if(elem.attributeType == "A") {
            return {description: elem.description, name: elem.name}
        }
    }).filter(Boolean);
},

Upvotes: 0

Related Questions