Created
October 8, 2020 20:22
-
-
Save capJavert/92dc35fe2ea387cc7f769140f426ae45 to your computer and use it in GitHub Desktop.
Require at least one of provided props
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
import PropTypes from 'prop-types' | |
/** | |
* Require at least one of provided props | |
* | |
* @example | |
* | |
* const requireOneOfProps = requireOneOf({ | |
* entity: PropTypes.string, | |
* entities: PropTypes.arrayOf(PropTypes.string) | |
* }) | |
* | |
* Component.propTypes = { | |
* entity: requireOneOfProps, | |
* entities: requireOneOfProps | |
* } | |
* | |
* @param {Object} propsToCheck | |
* @returns {Function} | |
*/ | |
const requireOneOf = propsToCheck => { | |
return (props, propName, compName) => { | |
const requirePropNames = Object.keys(propsToCheck) | |
const found = requirePropNames.find(propRequired => props[propRequired]) | |
try { | |
if (!found) { | |
throw new Error(`One of ${requirePropNames.join(',')} is required by '${compName}' component.`) | |
} | |
PropTypes.checkPropTypes(propsToCheck, props, propName, compName) | |
} catch (e) { | |
return e | |
} | |
return null | |
} | |
} | |
export { requireOneOf } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment