In the official React documentation, it is stated that one can specify a custom validator for type checking.
My custom implementation of a validator below does however never execute and I cannot figure out why that is.
In the following example, funcWithArgs should be used to validate a function based on the # of its arguments, as for instance an "onClick" function here takes 1 single arg. However, funcWithArgs never executes.
const funcWithArgs = argCount => (props, propName, componentName) => {
var func = props[propName];
if (typeof func !== 'function' || func.length !== argCount) {
return new Error(
`${propName} must be a function with ${argCount} number arguments`,
);
}
};
Component.propTypes = {
onClick: funcWithArgs(1)
}
What am I missing?
funcWithArgs is executing. It's returning an error, which isn't being handled. Replacing return new Error with console.log prints the propName message in a browser console, demonstrating that the function is being called.
Code Sandbox
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