15

I have a track prop with the following definition:

  propTypes: {
    track: React.PropTypes.shape({
      cover: React.PropTypes.string,
      title: React.PropTypes.string,
      artist: React.PropTypes.string
    })
  }

I would like the track.cover to get a default value if undefined:

getDefaultProps: function() {
    return {
      track: {
          cover: 'placeholder.png'
        }
      }
  }

Any chance I can do that at the view level? Does getDefaultProps does a Deep Merge? Or do I need to handle this at the model level?

Thanks

1 Answer 1

8

getDefaultProps does not merge passed property values with the return value specified. If the property does not exist, React will use the object returned by getDefaultProps to initialize the component instance.

The code below for example produces:

Test Cover and

Code:

var TrackItem = React.createClass({
  render: function() {
    var track = this.props.track;
    return (<div>{track.cover} and {track.artist}</div>);
  },
  getDefaultProps: function() {
    return {
      track: {
          artist: 'def artist'
        }
      }
  }        
});

var track = {
    cover: 'Test Cover'    
};
React.render(<TrackItem track={ track } />, mountNode);

Also, note that objects returned in getDefaultProps are shared across all instances of a component (reference).

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

5 Comments

Yup. I found this issue requiring the same feature: github.com/facebook/react/issues/2568 I'm waiting for discussion now, if you want to check that out. I think it makes sense to add the deep merge in some certain cases!
I'm not sure that the complexity of handling the variety of cases is really worth it though.
It doesn't actually sounds much complicated to me though. I think I could PR that if it gets validated.
#1) Not everyone would want/need it (and it could break existing components if not made optional), #2) The equivalent could be easily handled elsewhere in the object life-cycle, #3) Would arrays be merged (especially if the elements are objects)? #4) Would need ways to indicate a property should be undefined, yet not take default, #5) for large object structures, could needlessly bloat memory in lists with lots of defaults (copies), etc. Also -- how would this interact with the normal lifecycle events?
@WiredPrairie #3 is a good point, but come on... you don't name things as defaultProps with an implementation which does shallowMerge. This means usage of defaultProps is absolutely limited to a flat object structure. At least enforce some constraints throwing a warning if you have an object graph used for it. Geez...

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.