Ad

How To Render Unknown/variable Number Of React Elements

- 1 answer

I have this React component that looks like this:

 var TestResult = React.createFactory(React.createClass({

        displayName: 'test-result',

        getInitialState: function getInitialState() {
            return {
                active: false,
                testLines: []  //this value will update after AJAX/WebWorker completes
            };
        },

        makeNewState: function makeState(data) {
            this.setState(data);
        },

        componentDidMount: function () {

            var self = this;
            var testPath = this.props.testPath;

            setTimeout(function(){
                $.get(testPath).done(function (msg) {

                    var myWorker = new Worker('/js/workers/one.js');
                    myWorker.postMessage(msg);
                    myWorker.onmessage = function (msg) {

                        self.setState({testLines: msg.data.testLines});

                    };

                }).fail(function (err) {
                    console.error(err);
                });
            }, Math.random()*2000);

        },

        render: function() {

            var self = this;

            return React.createElement('p', {
                    className: this.state.active ? 'active' : '',
                    onClick: this.clickHandler,
                },
                self.state.testName, '  ', self.state.testLines, React.createElement('b', null, 'Pass/fail')
            );
        }

    }));

what I want is to render a variable number of components in the render function - the variable number is related to number of elements in the testLines array.

So, in order to do that, I might try changing the render method above:

 render: function() {

            var self = this;

            return React.createElement('p', {
                    className: this.state.active ? 'active' : '',
                },
                self.state.testName, '  ', React.createElement('div', self.state.testLines, React.createElement('b', null, 'Pass/fail')
            );
        }

so what I am trying to do is pass testLines, which is an array of React.createElement results, to React.createElement. Is this the correct way of doing it? "It" meaning rendering a variable number of React elements.

Ad

Answer

What you have to do is map over the array and create each of the sub-elements, then render those:

render: function() {
  var lines = this.state.testLines.map(function(line, i) {
    // This is just an example - your return will pull information from `line`
    // Make sure to always pass a `key` prop when working with dynamic children: https://facebook.github.io/react/docs/multiple-components.html#dynamic-children
    return (
      <div key={i}>I am a line!</div>
    );
  });

  return (
    <div id='lineContainer'>
      {lines}
    </div>
  );
};
Ad
source: stackoverflow.com
Ad