Reputation: 2743
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
...
Upvotes: 8
Views: 15536
Reputation: 1581
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>
Upvotes: 2
Reputation: 2090
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>
);
}
}
Upvotes: 16