Rohitas Behera Rohitas Behera - 3 years ago 160
React JSX Question

Unable to Append new Child Components in react

I am new to react. I have two issues . Here is the PLUNKER to it

First

I want to add another SingleButtonComponent when a SingleButtonComponent is clicked.
I am able to increment the number of children using a state variable numChildren.

AddChild: function() {
var numChildren = (this.state.numChildren) +1;
this.setState({numChildren :numChildren})
},


But I am getting error whenever I am trying to loop inside

render: function () {
return (
for (var i = 0; i < this.state.numChildren; i += 1) {
<SingleButtonComponent AddChild={this.AddChild}/>
};
)
}


I have temporarily kept the for loop out of render..

Please suggest me a way to add a child-component every time it is clicked.

Second :

I am getting this React.createClass is deprecated warning on plnkr . when I am adding the
createReactClass = require('create-react-class')

it is showing further error like "require is not defined"

Thanks

Answer Source

Your render function doesn't return anything.

If you're using React 16, try:

render: function() {
    const arr = [];
    for (var i = 0; i < this.state.numChildren; i += 1) {
        arr.push(<SingleButtonComponent key={i} AddChild={this.AddChild}/>);
    }
    return arr;
}

Otherwise, you must return a single element:

render: function() {
    const arr = [];
    for (var i = 0; i < this.state.numChildren; i += 1) {
        arr.push(<SingleButtonComponent key={i} AddChild={this.AddChild}/>);
    }
    return (<div>{arr}</div>);
}

Regarding your second question:
React.createClass is deprecated in favor of ES6 classes. Your component should be defined as follows:

class MainBody extends React.Component {
    constructor() {
        this.state = { numChildren: 0 };
    }

    AddChild() { ... }

    render() { ... }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download