Search code examples
javascriptreactjsreact-proptypes

Is there an easier way to define multiple condition Prop Types than by making own validator?


What if i would want prop to be type of number and in the same time required? As far as i know i have to make own validator for that. Is there any easier, elegant way?

function ShopxItem(props) {
    return (
        <>
            {props.name}
            {props.price}
        </>
    )
}

function PropTypesExample(){
    return (
        <>
            <ShopxItem name="1" price="xdd"></ShopxItem>
        </>
    )
}


ShopxItem.propTypes = {
//i would want to do it in that way but this overwrite "price" and returning an error "Duplicate Key xxx"
    price: PropTypes.number,
    price: PropTypes.isRequired,

// but as far as i know i have to do this like that
    price: (props, propName, componentName) => {
        let error;
        const prop = props[propName];
        if(prop === undefined || isNaN(prop)){error = new Error(`${componentName} price is required and have to be a number`);return error;}
        return null;
    },
}

Solution

  • Something like this should work:

    price: PropTypes.oneOfType([PropTypes.number, PropTypes.func]).isRequired
    

    We switched to using air-bnb's or for this purpose, instead of oneOfType, although I can't remember why exactly. In any case that package may also be of interest to you.