Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 947
GijsjanB Avatar asked Dec 15 '15 10:12

GijsjanB


3 Answers

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);
like image 73
Alexandre Kirszenberg Avatar answered Oct 19 '22 15:10

Alexandre Kirszenberg


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)
])
like image 31
Mike D Avatar answered Oct 19 '22 14:10

Mike D


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

like image 26
sammysaglam Avatar answered Oct 19 '22 14:10

sammysaglam