GijsjanB
GijsjanB

Reputation: 10042

Extract/read React propTypes

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?

Upvotes: 17

Views: 3668

Answers (3)

sammysaglam
sammysaglam

Reputation: 433

take a look at: https://www.npmjs.com/package/axe-prop-types this will allow you to extract all prop-types

Upvotes: 1

Alexandre Kirszenberg
Alexandre Kirszenberg

Reputation: 36418

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);

Upvotes: 6

Mike D
Mike D

Reputation: 251

Maybe adding a code example of what you are trying to do as I don't quite understand but why are you accessing propTypes? PropTypes don't contain values but rather expectations of what your value types should be for the different props passed into the component.

If you have a form that lets you alter the props I assume you are passing in the prop into the component that will be rendering the select component.You can access these props through props object.

If you are trying to validate the propTypes that can have the form of different types the following can be used:

optionalUnion: React.PropTypes.oneOfType([
  React.PropTypes.string,
  React.PropTypes.number,
  React.PropTypes.instanceOf(Message)
])

Upvotes: 1

Related Questions