React, add components to component
I started learning React and I hit the first wall.
I have a list component that needs to display a list of strings + to add a new line.
Everything in these two lines:
https://gist.github.com/matiit/7b361dee3f878502e10a
https://gist.github.com/matiit/8bac28c4d5c6ce3993c7
The addRow method is executed on click because I can see the .log console but no InputRows are added.
I can't figure out why.
This is a little updated (dirty) code that doesn't work either. Now this is just one file:
var InputList = React.createClass({
getInitialState: function () {
return {
rowCount: 1
}
},
getClassNames: function () {
if (this.props.type === 'incomes') {
return 'col-md-4 ' + this.props.type;
} else if (this.props.type === 'expenses') {
return 'col-md-4 col-md-offset-1 ' + this.props.type;
}
},
addRow: function () {
this.state.rowCount = this.state.rowCount + 1;
this.render();
},
render: function () {
var inputs = [];
for (var i=0;i<this.state.rowCount; i++) {
inputs.push(i);
}
console.log(inputs);
return (
<div className={ this.getClassNames() }>
{inputs.map(function (result) {
return <InputRow key={result} />;
})}
<div className="row">
<button onClick={this.addRow} className="btn btn-success">Add more</button>
</div>
</div>
);
}
});
source to share
this.render()
doing nothing. If you look at the function, it just does some calculation and returns some data (virtual dom nodes).
You should use setState instead of direct modification. It is cleaner and allows you to react to something that has changed.
addRow: function () {
this.setState({rowCount: this.state.rowCount + 1});
},
source to share