for (var i = 0; i < mas.length; i++) { ReactDOM.render( React.createElement('div', {className: "message"}, mas[i]), document.getElementById('blockofMessages') ); } 

How can I output data in a loop using React, what would it add blocks and not overwrite the data in the same block?

    1 answer 1

    You need to first prepare a set of elements for display, and only then display them in the DOM tree through ReactDOM.render . If you are not using JSX, then your code might look like this:

     // Генерируем массив элементов для отображения. var children = []; for (var i = 1; i < 5; i++) { children.push(React.createElement('div', null, i)); } // Отрисовываем элементы в DOM. ReactDOM.render( React.createElement('div', null, children), document.getElementById('container') ); 

    And here is a working example on JSFiddle.

    If you need to draw a certain pre-existing array in the DOM, then instead of the for loop, you can use the Array.prototype.map function:

     var items = [1, 2, 3, 4]; ReactDOM.render( React.createElement('div', null, items.map(function(item) { return React.createElement('div', null, item); })), document.getElementById('container') ); 

    Well, if you use JSX (and ES6), then the code can be written even more elegantly:

     const items = [1, 2, 3, 4]; ReactDOM.render( (<div>{items.map(item => <div>{item}</div>)}</div>), document.getElementById('container') );