Skip to content

Instantly share code, notes, and snippets.

@pbojinov
Last active July 10, 2018 23:44
Show Gist options
  • Save pbojinov/7174cb3e820113b5a620151bd82fb7a1 to your computer and use it in GitHub Desktop.
Save pbojinov/7174cb3e820113b5a620151bd82fb7a1 to your computer and use it in GitHub Desktop.
// Andrew Clark's explanation: https://github.com/facebook/react/issues/9125#issuecomment-285531461
// ---
// Checking for isRequired on custom validator
// PropTypes source: https://github.com/facebook/prop-types/blob/master/factoryWithTypeCheckers.js#L206-L217
// -------------------------------------------------------------------------------------------------------
// This is a factory function (also called a higher-order function)
function createCustomPropType(isRequired) {
// The factory returns a custom prop type
return function(props, propName, componentName) {
const prop = props[propName];
if (prop == null) {
// Prop is missing
if (isRequired) {
// Prop is required but wasn't specified. Throw an error.
throw new Error();
}
// Prop is optional. Do nothing.
} else {
// Put your validation logic here...
}
}
}
// Using the factory, create two different versions of your prop type
const customPropType = createCustomPropType(false);
customPropType.isRequired = createCustomPropType(true);
// Now this will work:
MyComponent.propTypes = {
optional: customPropType,
required: customPropType.isRequired,
};
import React from 'react';
import PropTypes from 'prop-types';
class MyComponent extends React.Component {
render() {
// ... do things with the props
}
}
MyComponent.propTypes = {
// You can also specify a custom validator. It should return an Error
// object if the validation fails. Don't `console.warn` or throw, as this
// won't work inside `oneOfType`.
customProp: function(props, propName, componentName) {
if (!/matchme/.test(props[propName])) {
return new Error(
'Invalid prop `' + propName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment