1

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')
                );
4
  • change return dom_content; to return {dom_content}; Commented May 24, 2018 at 9:21
  • Which version of React ? Commented May 24, 2018 at 9:22
  • You are using a VEERY old React Version. Thats not how you do that nowadays. Id recommend you to use the latest react version. Commented May 24, 2018 at 9:22
  • Okay I will try the latest react version Commented May 24, 2018 at 9:26

2 Answers 2

2

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>
    )
}
Sign up to request clarification or add additional context in comments.

Comments

0

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>));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.