React props - set isRequired on a prop if another prop is null / empty

sandrina-p picture sandrina-p · Feb 17, 2017 · Viewed 17.7k times · Source

I have a component <Button>.
If the component doesn't has this.props.children, I want to set the prop ariaLabel as isRequired, otherwise in can be optional. How do I do that?

ariaLabel prop not required:

<Button>Add to bag</Button>

ariaLabel prop has to be required:

<Button ariaLabel="Add to bag" icon={ favorite } />

if this.props.children and this.props.ariaLabel are empty, it throws an error saying that this.props.ariaLabel is isRequired

<Button icon={ favorite } />

propTypes:

Button.propTypes = {
    /** icon inside Button. */
    icon: React.PropTypes.object,
    /** Content inside button */
    children: React.PropTypes.node,
    /** Aria-label to screen readers */
    ariaLabel: React.PropTypes.string, /*isRequired if children is empty */
};

Thanks

Answer

chickenchilli picture chickenchilli · Sep 21, 2017

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!');
        }
    },

}