Unable to Append new Child Components in react

310 views Asked by At

I am new to react.

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

. Here is the PLUNKER to it

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.

Thanks

1

There are 1 answers

5
Orrrr On BEST ANSWER

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() { ... }
}