June June - 23 days ago 18
React JSX Question

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

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?

Answer

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.

Comments