Reputation: 63667
In React propTypes, is it possible to specify that one prop or another prop must be provided?
For example, if myPropA
is not provided, then you must provide myPropB
.
Docs don't appear to have a method for this.
Upvotes: 0
Views: 365
Reputation: 38807
You can specify an optional prop type for myPropA
, then provide a custom validation prop function for myPropB
. You can supply any custom error message you would want in whatever structure you need. You can use the function arguments such as the prop name and component name to build this message. This example also uses only the property names myPropA
/myPropB
instead of introducing aan additional custom property key/name.
import React from 'react';
import PropTypes from 'prop-types';
const Hello = ({ name, myPropA, myPropB }) => <h1>Hello {name}!</h1>;
Hello.propTypes = {
myPropA: PropTypes.string,
myPropB: function(props, propName, componentName) {
// required validation
if(!props.myPropA && !props.myPropB) {
return new Error(`Failed prop type: The prop '${propName}' is required in '${componentName}' when prop 'myPropA' is 'undefined', but it's value is '${props[propName]}'.`);
}
// string validation
if(!props.myPropA && props.myPropB && typeof props.myPropB !== 'string') {
return new Error(`Failed prop type: Invalid prop ${propName} of type '${typeof props[propName]}' supplied to ${componentName}, expected 'string'.`);
}
},
};
export default Hello;
Here is an example in action.
Hopefully that helps!
Upvotes: 1