Reputation: 21
How to use the reactJS to append DOM elements with loop.
I use the way Click here
After compiler these code still get the error with :
Uncaught Error: Content.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
var Content = React.createClass({
render: function () {
var dom_content = [];
for (var i = 0; i < 3; i++) {
dom_content.push(<li className='col-xs-12 col-sm-6 col-md-4 block'><div className='box'></div></li>);
}
return dom_content;
}
});
ReactDOM.render(
<Content />,
document.getElementById('the_box')
);
Upvotes: 1
Views: 2929
Reputation: 78
You are pushing them to an array object called dom_content. As the error message suggests, you can return only react elements from render method. In this case you're returning a javascript object. Try something like:
new Array(3).map(() => (<li className='col-xs-12 col-sm-6 col-md-4 block'><div className='box'></div></li>));
Upvotes: 0
Reputation: 4008
dom_content
is an array.
You need React 16 to directly render it.
You can now return an array of elements from a component’s render method. Like with other arrays, you’ll need to add a key to each element to avoid the key warning
If you don't want to/cannot use React 16, wrap it in a div.
render: function () {
var dom_content = [];
for (var i = 0; i < 3; i++) {
dom_content.push(
(
<li
key={i} // Add this too =)
className='col-xs-12 col-sm-6 col-md-4 block'
>
<div className='box'></div>
</li>
)
);
}
return (
<div> // or <ul> ??
{dom_content}
</div>
)
}
Upvotes: 2