Extract/read React propTypes

- 1 answer

Ad

I want to visually test React components. The user can alter the component's props using a form. I would like to be able (for example) to render a <select> based on React.PropTypes.oneOf(['green', 'blue', 'yellow']).

When I read MyComponent.propTypes it returnes a function defined by React. Is there a way to extract/read the prop types?

Ad

Answer

Ad

You can't read directly from propTypes since, as you said, they are defined as functions.

You could instead define your propTypes in an intermediary format, from which you'd generate your propTypes static.

var myPropTypes = {
  color: {
    type: 'oneOf',
    value: ['green', 'blue', 'yellow'],
  },
};

function processPropTypes(propTypes) {
  var output = {};
  for (var key in propTypes) {
    if (propTypes.hasOwnProperty(key)) {
      // Note that this does not support nested propTypes validation
      // (arrayOf, objectOf, oneOfType and shape)
      // You'd have to create special cases for those
      output[key] = React.PropTypes[propTypes[key].type](propTypes[key].value);
    }
  }
  return output;
}

var MyComponent = React.createClass({
  propTypes: processPropTypes(myPropTypes),

  static: {
    myPropTypes: myPropTypes,
  },
});

You could then access your custom propTypes format via MyComponent.myPropTypes or element.type.myPropTypes.

Here's a helper to make this process a little easier.

function applyPropTypes(myPropTypes, Component) {
  Component.propTypes = processPropTypes(myPropTypes);
  Component.myPropTypes = propTypes;
}

applyPropTypes(myPropTypes, MyComponent);
Ad
source: stackoverflow.com
Ad