6

I'm trying to produce a bunch of divs (to play around with infinite scroll). I'm trying to do this:

var arr = [];

for (i = 0; i<10; i++) {

  arr.push(i);

}

class List extends React.Component{

  render() {

    var longlist = "";

      arr.forEach(function(item,index){

         longlist += '<div>' + item + '</div>';

      });

    return (<div>{longlist}</div>);

  }
}

I'm getting the following output:

<div>0</div><div>1</div><div>2</div><div>3</div><div>4</div><div>5</div><div>6</div><div>7</div><div>8</div><div>9</div>

What should I do so that I get rendered divs instead of a string? That is, the output looks like this:

1
2
3
...
thanks_in_advance
  • 2,603
  • 6
  • 28
  • 44
  • Im not sure what you're asking exactly. Based on the code it appears it's working as intended. The function is putting the numbers 0-9 into separate divs and rendering them to the page in a single div correct? – Zach Harriott Aug 20 '17 at 16:41
  • @ZachHarriott I want rendered divs, I'm getting raw divs: http://jsbin.com/kariwe/1/edit?html,js,output – thanks_in_advance Aug 20 '17 at 16:46
  • Possible duplicate of [loop inside React JSX](https://stackoverflow.com/questions/22876978/loop-inside-react-jsx) – Mayank Shukla Aug 20 '17 at 16:50

2 Answers2

14

Use .map() and simple JSX to return the divs that you want.

class List extends React.Component{

  render() {

    var renderedOutput = arr.map(item => <div> {item} </div>)

    return (
      <div>
        {renderedOutput}
      </div>
    );
  }
}
Christopher Messer
  • 2,040
  • 9
  • 13
  • 4
    And to explain further: the original code creates a *string* and adds the HTML code into it. This will of course result in the text that is shown, not actual HTML code. This code creates elements and puts the desired output inside them, which causes HTML to be rendered. – Sami Kuhmonen Aug 20 '17 at 16:45
2

Another way you could also do it like this

class DivList extends React.Component {
      
      constructor(props) {
        super(props);
      }
              
displayForm() { 

 let divs = [];
  for(let i = 0; i < 10; i++) {
       divs.push (<div key={i} >{i}</div>)
   }
   return divs;
}
              
  render() { return (  <div>{this.displayForm()} </div> ); }
}
ReactDOM.render(<DivList />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.min.js"></script>

<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>
abdul
  • 1,531
  • 1
  • 14
  • 29
  • You should add a unique key to each child or element in the array. updated the answer that should get rid of the error. – abdul Aug 20 '17 at 17:08