A way to make a custom proptype required would be useful. Maybe some form of the createChainableTypeChecker factory could be exposed?
I'm wary of exposing an API for this. As you can see, it's really just quick sugar for checking whether the prop is undefined. Adding a props[propName] == null
check to your custom validator does the same thing.
Yeah, I think the main benefit of exposing something for this wouldn't be providing a way of making a prop required, but instead providing a way of having the option of making it required:
var MyPropType = chainablePropTypeFactory(function () {
// prop type validation here.
});
propTypes: {
prop: MyPropType,
requiredProp: MyPropType.isRequired
}
So that a custom prop type can easily be created and used for both optional and required props.
I was about to file a similar issue, my main reason was to not have to duplicate the error handling of isRequired. This changed from 0.10 to 0.11 for example (not documented) and led to some issues in my code during the migration. Separately it is a nice UX if error messages stay consistent. My code looks something like this, which is really just duplication of some code in createChainableTypeChecker.checkType:
myProp: function(props, propName, componentName) {
if (props[propName] == null) {
return new Error("Warning: Required prop `" + propName +
"` was not specified in `" + componentName +
"`)");
} else ...
},
Also wary of exposing an API for this. In the long term you can use Flow or other systems and we'll probably move propTypes out of core eventually.
It's old, but agreeing with what @lettertwo wrote, it could look like this until we get an exposed API:
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;
}
And later:
const customProp = chainablePropType(() => {...});
const propTypes = {
prop: customProp,
requiredProp: customProp.isRequired
};
In case this still might be helpful to somebody.
It would also be useful so checkers like eslint could tell when default props were needed for a custom property.
Most helpful comment
It's old, but agreeing with what @lettertwo wrote, it could look like this until we get an exposed API:
And later:
In case this still might be helpful to somebody.