14

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();
    }
}

3 Answers 3

11

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

component.defaultProps = {
  foo: () => {},
};
Sign up to request clarification or add additional context in comments.

Comments

4

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

getDefaultProps: function() {
    return {
        onClick: function() {}
    };
}

1 Comment

ES6 class syntax for the same: "static defaultProps = { onClick: () => {} };"
0

You could do with typeof:

if (typeof this.props.onClick === 'function'){
    //...
}

Comments

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.