I am having issues with removing stateful elements in an React array. In the following example, if you click 'toggle' on the second element ('B'), you will see:
Entry id: 0 name: A Is Active Toggle Remove
Entry id: 1 name: B Is Not Active Toggle Remove
Entry id: 2 name: C Is Active Toggle Remove
If you now click 'Remove' on the first element ('A'):
Entry id: 0 name: B Is Active Toggle Remove
Entry id: 1 name: C Is Not Active Toggle Remove
B has changed, but all I wanted to do was delete A and not impact any other elements. I've got a key as per the docs, and have tried using a key with a string prefix but it didn't help.
Is there any way to do this without pushing state up to TestContainer? (In my real situation I have a lot of disparate elements with different types of states).
<div id="test"></div>
<script type="text/jsx">
var TestLine = React.createClass({
getInitialState: function() {
return {active: true};
},
handleLineRemove: function(e) {
this.props.processLineRemove(this.props.id);
},
toggleActive: function(e) {
this.setState({active: !this.state.active};
},
render: function() {
return (
<p>
Entry id: {this.props.id} name: {this.props.name}
{this.state.active ? " Is Active " : " Is Not Active " }
<a onClick={this.toggleActive}>Toggle</a>
<a onClick={this.handleLineRemove}>Remove</a>
</p>
);
}
});
var TestContainer = React.createClass({
getInitialState: function() {
return {data: {lines: ['A','B','C']}};
},
processLineRemove: function(index) {
var new_lines = this.state.data.lines.slice(0);
new_lines.splice(index,1);
var newState = React.addons.update(this.state.data, {
lines: {$set: new_lines}
});
this.setState({data: newState});
},
render: function() {
var body =[];
for (var i = 0; i < this.state.data.lines.length; i++) {
body.push(<TestLine
key={i}
id={i}
name={this.state.data.lines[i]}
processLineRemove={this.processLineRemove} />)
}
return (
<div>{body}</div>
);
}
});
React.render(<TestContainer />, document.getElementById('test'));
</script>
TestContainerand how to re-render correctly. It looks like the answer should help you.