3

Assume a component receives a nested property in React from its parent :

getDefaultProps: function(){
    return ({
        "data" : {
            "style": {
                pieChart: true, // otherwise it'd be a donut chart
                radius: 100
            },
            "series": {
                "data": []
            }
        }
    });
},

It's possible to receive a property with some missing values (e.g we may receive series but not style , or we may receive a value for radius but not for pieChart)

How can we define default values only for the missing values ? and keep the rest of values as they are received

0

2 Answers 2

2

you can't set the default values for deep objects in the getDefaultProps method but you can inside the componentWillMount method.

React.createClass({
  getDefaultProps() {
    return {
      "data" : {
        "style": {
          pieChart: true, // otherwise it'd be a donut chart
          radius: 100
        },
        "series": {
          "data": []
        }
      }
    }
  },

  componentWillMount() {
    if(!this.props.data.style) {
      this.props.data.style = {
        pieChart: true,
        radius: 100
      };
    }
    if(!this.props.data.series) {
      this.props.data.series = {
        data: []
      };
    }
  }
});

however this is not recommended as React best practices state that you shouldn't modify this.props from within the component. What you really should do is use the logic in componentWillMount to format the object to your liking before you pass it into the component.

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

Comments

0

Props are meant to be overwritten. You can use the componentWillReceiveProps function to handle any negotiation between the old props and the new props, but you will have to write out the logic yourself. Not totally sure of what you're data structure looks like, but I'm sure you could do the job with underscore's _.extend and _.defaults.

2 Comments

The problem is "componentWillReceiveProps" is not called for the initial render .
will you have variable data even for the initial render? if not, getDefaultProps will do the job then, and componentWillReceiveProps will do the job subsequently. if the data is variable, you can simply transform props in the render method. duplicating logic like that is fairly common, IMO. In my company's flux stack, we often do similar and sometimes identical things for getInitialState and for when the store changes.

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.