Reputation: 12179
How can I remove an item from the data
when clicking the div inside Item?
var App = React.createClass({
...
handleSubmit: function(e) {
this.state.data.push({ x: this.state.x });
}
});
The item's class to remove.
var Item = React.createClass({
render: function() {
return (
<li>
<div onClick={this.removeItem}></div>
</li>
)
}
});
The list class.
var ItemList = React.createClass({
render: function() {
var items = this.props.data.map(function(item) {
return <Item x={item.x}>
});
}
});
Upvotes: 1
Views: 3076
Reputation: 3252
Since the App
component manages the data
array, you need to bubble the remove request all the way from Item
to ItemList
to App
.
So pass a callback from App
to ItemList
:
var App = React.createClass({
...
removeItem: function(index) {
this.setState(function(state) {
var newData = state.data.slice();
newData.splice(index, 1);
return {data: newData};
});
},
render: function() {
return (
... <ItemList onRemove={this.removeItem} /> ...
);
},
...
});
And pass that callback into each Item
:
var ItemList = React.createClass({
render: function() {
var items = this.props.data.map(function(item, index) {
return <Item x={item.x} index={index} onRemove={this.props.onRemove}>
}.bind(this));
...
}
});
Finally, call onRemove
from Item
:
var Item = React.createClass({
...
removeItem: function() {
this.props.onRemove(this.props.index);
},
});
Upvotes: 4