Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react prop-types: custom validators not firing

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?

like image 547
Thierry Prost Avatar asked Jul 12 '26 23:07

Thierry Prost


1 Answers

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

like image 114
Jake Worth Avatar answered Jul 14 '26 13:07

Jake Worth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!