Reactjs - proptypes check with oneOfType
Asked Answered
E

2

5

I want to allow a component to having one of two possible proptypes (string or undefined). I am using PropTypes.oneOfType to do this.

import React from 'react';
import PropTypes from 'prop-types';

Product.propTypes = {
    productTag: PropTypes.oneOfType([
        PropTypes.string, undefined
    ]),
};

Product.defaultProps = {
    productTag: undefined
};

Is that the correct way?

Earthwork answered 19/8, 2020 at 15:55 Comment(0)
T
4

import React from 'react';
import PropTypes from 'prop-types';

Product.propTypes = {
    productTag: PropTypes.oneOfType([
        PropTypes.oneOf([undefined, PropTypes.string])
    ]),
};

OR

Product.propTypes = {
    productTag: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.oneOf([undefined])
    ]),
};

Product.defaultProps = {
    productTag: undefined
};

I think you can do it this way, by using PropTypes.oneOf. I don't think passing only undefined it works.

Twohanded answered 19/8, 2020 at 15:59 Comment(0)
F
2

If the property is undefined then that really means it isn't present, i.e., what you are trying to express is that the productTag property is optional, but when present it needs to be a string. Is that right?

As the documentation states, "By default, these are all optional.". So in that case you can simply use:

Product.propTypes = {
    productTag: PropTypes.string
};

since you are not marking it as isRequired.

Flaherty answered 19/8, 2020 at 16:3 Comment(2)
So, if I wanted to render a element if the productTag not undefined and has value, like this.props.productTag && <span className="p__tag">{this.props.productTag}</span> This will work?Earthwork
On this component will be used in several components as child and some of them not passing productTag props to this and that is my main purpose to add propstype and defautProps.Earthwork

© 2022 - 2024 — McMap. All rights reserved.