Skip to content

Instantly share code, notes, and snippets.

@namxam
Created March 28, 2017 13:43
Show Gist options
  • Save namxam/60ed51bdc365435d09040f899562b2ff to your computer and use it in GitHub Desktop.
Save namxam/60ed51bdc365435d09040f899562b2ff to your computer and use it in GitHub Desktop.
React custom validator with isRequired support
const chainablePropType = predicate => {
const propType = (props, propName, componentName) => {
// don't do any validation if empty
if (props[propName] == null) {
return;
}
return predicate(props, propName, componentName);
}
propType.isRequired = (props, propName, componentName) => {
// warn if empty
if (props[propName] == null) {
return new Error(`Required prop \`${propName}\` was not specified in \`${componentName}\`.`);
}
return predicate(props, propName, componentName);
}
return propType;
}
const customProp = chainablePropType(() => {...});
const propTypes = {
prop: customProp,
requiredProp: customProp.isRequired
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment