Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Providing default value for function prop in React

Tags:

reactjs

What is the best way to handle optional React.PropType.func properties?

Should I provide default noop for it (if so what's the best way) or should I just check if the prop is defined?

propTypes: {
    onClick: React.PropTypes.func
},

someMethod: function() {
    if (this.props.onClick) {
       this.props.onClick();
    }
}
like image 830
lanan Avatar asked Sep 25 '15 14:09

lanan


2 Answers

i am using anonymous empty arrow function... correct me if this is stupid :)

component.defaultProps = {
  foo: () => {},
};
like image 103
Bimal Grg Avatar answered Oct 09 '22 10:10

Bimal Grg


React has getDefaultProps. Then you can call onClick without errors.

getDefaultProps: function() {
    return {
        onClick: function() {}
    };
}
like image 34
Rick Jolly Avatar answered Oct 09 '22 11:10

Rick Jolly