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.
Firstly, npm install / yarn add the prop-types package if you haven't already. Then, add your propTypes (and defaultProps too if required) after the stateless functional component has been defined, before you export it.
You 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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With