Ad

ReactJS - Creating Children Components By Looping Through Object

- 1 answer

I have parent and child component. I want the parent to render multiple child components with properties specified in an object. I cannot seem to make the loop in the render function work.

 var Inputs = React.createClass({
  propTypes: {
    type:      React.PropTypes.string,
    xmltag:      React.PropTypes.string,
    class:      React.PropTypes.string
  },
  getDefaultProps: function () {
    return { 
      type: ' text'
    };
  },
  render: function() {
    return (
      <div className={'form-element col-xs-6 col-sm-6 ' + this.props.class}>
        <label className="col-xs-12">{this.props.text}</label>
        <input className="col-xs-12" type={this.props.type} xmltag={this.props.xmltag}></input>
      </div>
      );
  },
});

 //OBJECT that needs to be rendered
 var formTags = {
  id: ["ID", "List ID", "text"],
  title: ["TITLE", "List Title", "text"],
  said: ["SAID", "SAID", "number"]
};

var InputList = React.createClass({
//PROBLEM STARTS HERE
  render: function() {
    for (var key in formTags) {
      return (
        //Not using everything from formTags
        <Inputs type="number" text={key}>
        );
    };
  },
 //PROBLEM ENDS HERE
});

ReactDOM.render(<InputList />, document.getElementById('mainForm'));
Ad

Answer

React component must have only one root element, now you are trying render several elements, add one root element, like in example (you can use any elements <div><p> etc.)

var InputList = React.createClass({
  render: function() {
    var inputs = Object.keys(this.props.tags).map(function (key) {
       return <Inputs key={ key } type="number" text={ key } />;
    });

    return <div>
      { inputs }
    </div>;
  }
});

Example

Ad
source: stackoverflow.com
Ad