Created
March 28, 2017 13:43
-
-
Save namxam/60ed51bdc365435d09040f899562b2ff to your computer and use it in GitHub Desktop.
React custom validator with isRequired support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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