Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`this.props` inside `getDefaultProps()` of React?

Tags:

reactjs

I'm trying to add a prop that depends on other props that will be basically passed by the component's owner component.

So I did:

propTypes: {
  user: React.PropTypes.object,
  comment: React.PropTypes.object
},

getDefaultProps: function() {
  return {
    admire: new Admire({
              user: this.props.user, 
              comment:this.props.comment
            })
  };
}

But it seems like props user and comment are not accessible at getDefaultProps call time.

Is there any way to define a default prop that depends on other props that will be passed from owner components?

like image 535
June Avatar asked Oct 14 '15 12:10

June


1 Answers

getDefaultProps is called before any instances are created and thus cannot rely on this.props. It's meant to get the default props in case the owner hasn't passed them.

An alternate solution would be to use getInitialState as this would give you access to this.props.user and this.props.comment.

like image 108
Eric Avatar answered Oct 24 '22 09:10

Eric