React props - set isRequired on a prop if another prop is null / empty
Solution 1:
You don't need another library, 'prop-types' provides this out of the box. See https://facebook.github.io/react/docs/typechecking-with-proptypes.html
Example:
import PropTypes from 'prop-types';
//.......
ExampleComponent.propTypes = {
showDelete: PropTypes.bool,
handleDelete: function(props, propName, componentName) {
if ((props['showDelete'] == true && (props[propName] == undefined || typeof(props[propName]) != 'function'))) {
return new Error('Please provide a handleDelete function!');
}
},
}
Solution 2:
This may be exactly what you need: https://github.com/thejameskyle/react-required-if
In your case, your propTypes would be:
import requiredIf from 'react-required-if';
Button.propTypes = {
/** icon inside Button. */
icon: React.PropTypes.object,
/** Content inside button */
children: React.PropTypes.node,
/** Aria-label to screen readers */
ariaLabel: requiredIf(React.PropTypes.string, props => !props.children), /*isRequired if children is empty */
};