I am using React.js to dynamically create a html table containing text boxes. I have rows that can be removed by a button click. I expect, when I click "remove" on the first row that the table re-renders with row 1 removed. However, when react re-draws the table, it looks like it always removes the last row of the table from the DOM instead of using the actual values from my state object. Perhaps I found a bug? Here's my code:
/** @jsx React.DOM */
var MyApp = React.createClass({
getInitialState: function () {
return {
col_one: ['c1r1', 'c1r2', 'c1r3'],
col_two: ['c2r1', 'c1r2', 'c1r3'],
col_three: ['c3r1', 'c3r2', 'c3r3']
}
},
handleCellChange: function (colName, index, e) {
console.log('onChange:', colName, index, e.target.value);
},
handleRemove: function (i) {
var that = this;
console.log('removing row:',i);
_.forEach(this.state, function (val, colName) {
that.state[colName].splice(i,1); // BUG???
//_.pullAt(that.state[key], i); // doesn't work either
});
console.log(this.state);
this.setState(this.state);
},
render: function() {
var that = this,
rows = [],
cols = _.keys(this.state);
rows.push(
<tr>
{cols.map(function (col) {
return (
<th>{col}</th>
)
})}
</tr>
)
for (var i = 0; i < this.state[cols[0]].length; i++) {
rows.push(
<tr>
{cols.map(function (col) {
return (
<td>
<input type="text" defaultValue={that.state[col][i]} onChange={that.handleCellChange.bind(that, col, i)} />
</td>
)
})}
<td>
<button onClick={this.handleRemove.bind(this, i)}>Remove</button>
</td>
</tr>
)
}
return (
<table>
<tbody>
{rows}
</tbody>
</table>
);
}
});
React.renderComponent(<MyApp />, document.body);