Created
September 14, 2016 01:58
-
-
Save bbstilson/ad9cb64e787b90f4128ecef4ef707c45 to your computer and use it in GitHub Desktop.
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
/** | |
* Custom PropType for checking multiple PropTypes. | |
* | |
* Returns an error if the prop does not pass one of the PropType checks. | |
* Sourced from: http://stackoverflow.com/a/31169012 | |
* | |
* @param {mixed} any valid React PropType (element|string|arrayOf|shape|...) | |
* | |
* @returns {error} returns an error if all fail | |
*/ | |
export const somePropType = (...types) => { | |
return (...args) => { | |
// PropTypes are functions that return null if they pass and an error if they fail. | |
// So, by checking if at least one of the functions returned null, then we know that | |
// one of the PropType checks passed. | |
// If all are non-null, then we want to log both of throw an error with both of those messages. | |
const errors = types.map((type) => type(...args)); | |
const passed = errors.some(resp => resp === null); | |
if (!passed) { | |
// Didn't pass any of the PropType checks. | |
// Collect the error messages and join them together. | |
const message = errors.map((e) => e.message).join('\n'); | |
return new Error(message); | |
} | |
return; | |
} | |
} | |
// Usage | |
import React from 'react'; | |
import { somePropType } from './SomePropType.js'; | |
const { element, arrayOf } = React.PropTypes; | |
MyComponent.propTypes = { | |
// Ensures anImportantValue is either an element or an array of elements. | |
anImportantValue: somePropType(element, arrayOf(element)) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment