What I have is a list of items, where each of the Item
Component have a delete button that will make a call to the deleteItem
function in the List
component to update its state. The deleteItem
function will need the parent instance bound to it to call this.setState
.
Currently I'm passing parent={this}
along with deleteHandler={this.deleteItem}
when the List
renders the Item
. So that when the Item
calls the handler, it will have access to the parent instance.
onClick={this.props.deleteHandler.bind(
this.props.parent,
this.props._key
)}
But this feels unnecessary, and I'm wondering if there's a better way to achieve what I want to do. (ie. some kind of built in linkage between child and parents, or a better way to pass/call the function)
Child Component
class Item extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<li>
{this.props.value}
<button
className="delete"
onClick={this.props.deleteHandler.bind(
this.props.parent,
this.props._key
)}
>
x
</button>
</li>
);
}
}
Parent Component
class List extends React.Component {
constructor(props) {
super(props);
this.state = {
items: []
};
}
renderItem(item) {
return (
<Item
key={item.key}
value={item.value}
_key={item.key}
deleteHandler={this.deleteItem}
parent={this}
/>
);
}
addItem() {
// ...
}
deleteItem(key) {
this.setState(prevState => ({
items: prevState.items.filter(function(obj) {
return obj.key !== key;
})
}));
}
render() {
var items = [];
for (var i = 0; i < this.state.items.length; i++) {
items.push(this.renderItem(this.state.items[i]));
}
return (
<React.Fragment>
<ul>{items}</ul>
<button className="addItem" onClick={this.addItem.bind(this)}>
Add Value
</button>
</React.Fragment>
);
}
}
Thanks!