I am specifying a required function proptype in a react (version 0.13.3) component...
var MyComponent = React.createClass({
propTypes : {
onClick : React.PropTypes.func.isRequired
},
handleClick(event) {
this.props.onClick(event, clickCallback);
},
clickCallback() {
console.log("foo");
},
render() {
return <div onClick={this.handleClick}></div>
}
});
export default MyComponent;
As you can see my onClick prop not only needs to be a function but needs to accept 2 arguments. is there any way to specify this using React PropTypes?
I have read the React docs entry on re-usable components and there seems to be only a way to define the shape of an object type but not a function type.
I am specifying a required function proptype in a react (version 0.13.3) component...
var MyComponent = React.createClass({
propTypes : {
onClick : React.PropTypes.func.isRequired
},
handleClick(event) {
this.props.onClick(event, clickCallback);
},
clickCallback() {
console.log("foo");
},
render() {
return <div onClick={this.handleClick}></div>
}
});
export default MyComponent;
As you can see my onClick prop not only needs to be a function but needs to accept 2 arguments. is there any way to specify this using React PropTypes?
I have read the React docs entry on re-usable components and there seems to be only a way to define the shape of an object type but not a function type.
Share Improve this question edited Oct 22, 2015 at 10:41 danbahrami asked Oct 22, 2015 at 10:27 danbahramidanbahrami 1,0121 gold badge9 silver badges14 bronze badges 5 |2 Answers
Reset to default 14You could try using a custom validator:
propTypes : {
onClick : function(props, propName, componentName) {
var fn = props[propName];
if(!fn.prototype ||
(typeof fn.prototype.constructor !== 'function' &&
fn.prototype.constructor.length !== 2)) {
return new Error(propName + 'must be a function with 2 args');
}
}
}
Ok, I checked this a bit, and this could be the answer (unable to test it right now). So, you can pass validating functions for PropTypes, like:
propTypes : {
onClick : function(props, propName, componentName) {
if (!props.event || !props.callback) {
return new Error('Too few arguments');
}
}
}
Check this article for details: http://developer.fortnox.se/blog/proptypes-in-react-js/
React.PropTypes.shape
, but apparently that can't be used with functions. – Samuli Hakoniemi Commented Oct 22, 2015 at 10:58