Faisal Mushtaq Faisal Mushtaq - 26 days ago 10
React JSX Question

React PropTypes. Force an Array to be of a specific React Type

How can I force/validate that each item of a passed in Array prop (to a React Component), be of a specific React type?

Here is an example code for this:

<div id="container"></div>

<script type="text/jsx">
var MyButton = React.createClass({
render: function() {
return (<input type="button" value={this.props.text} />);
}
});

var MyButton2 = React.createClass({
render: function() {
return (<input type="button" value={this.props.text} />);
}
});

var MyComp = React.createClass({
propTypes: {
//buttons: React.PropTypes.arrayOf(MyButton) //Something like this
},
render: function() {
return (<div><div>{this.props.title}</div>
{this.props.buttons}
</div>
);
}
});

var buttons = [React.createElement(MyButton, {key:"3", text: "Save"})];
buttons.push(React.createElement(MyButton, {key: "1",text: "Cancel"}));
buttons.push(React.createElement(MyButton2, {key: "2",text: "Search"})); // And don't allow this one

React.render(<MyComp title="My Window" buttons={buttons} />, document.getElementById('container'));
</script>

Answer

As shown in this good article about propTypes, you can write your own extension function that can be passed to React.PropTypes.arrayOf.

This is the example shown in the post referenced above for email:

var emailPropType = function (props, propName, component) {
  if (!isEmail(props[propName])) {
    return new Error('Invalid email!');
  }
};

Can be used like this:

var EmailList = React.createClass({
  propTypes: {
    emails: React.PropTypes.arrayOf(emailPropType).isRequired
  },
  render: function () {
    return React.DOM.ul(null, this.props.emails.map(function (email) {
      return React.DOM.li({ key: email }, email);
    }));
  }
});