Reputation: 1734
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?
Upvotes: 5
Views: 9474
Reputation: 21364
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
.
Upvotes: 2
Reputation: 2655
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.
Upvotes: 4