Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Nested defaultProps deep merge

Tags:

reactjs

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

like image 919
Augustin Riedinger Avatar asked Mar 22 '15 13:03

Augustin Riedinger


1 Answers

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).

like image 146
WiredPrairie Avatar answered Oct 02 '22 11:10

WiredPrairie