Extract/read React propTypes
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
Related Questions
Ad
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad