In a React component, if I declare:
MyComponent.propTypes = {
// An object that could be one of many types
header: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
}
How do I know if header is a string or a number in my render method?
In your render method, you could use the typeof operator to determine the type of the header variable. If you have something like Lodash, you could use one of its utility methods as well (_.isString, _.isNumber, etc.).
Note: Your comment "An object that could be one..." should probably be restated as "A variable that could be one..." since you're saying that it's not an object but rather either a string or a number.
Actually, if the value's type is one of primitive types (string, number ...), you can use the above approach of @jrubins.
For self-defined React components, you must check the associated field .type. Here is the demo code:
Steps.propTypes = {
// must not be an empty array of Step
children: PropTypes.arrayOf(function(props, propName) {
const value = props[propName];
if ( value.type !== Step) {
return new Error('Must supply an instance of Step');
}
}),
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With