Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Detect a variable's PropTypes

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?

like image 379
anhldbk Avatar asked Aug 04 '26 22:08

anhldbk


2 Answers

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.

like image 181
Jon Rubins Avatar answered Aug 06 '26 13:08

Jon Rubins


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');
    }
  }),
};
like image 38
anhldbk Avatar answered Aug 06 '26 14:08

anhldbk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!