'Binding this to the event handler in react js
I just read book about react js for beginner, but i have a trouble. This is just simple problem in button element as you can see there is an event handler that i pass an argument. The handler is useful for if we click the button then the element next to it will disappear. it works correctly if i just wrote this line
<button onClick={ () => this.onDismiss(item.objectID) } type="button"> // using arrow function
Because of performance issue i am looking for another way
The problem is how i can bind this
to the onDismiss
handler... i've tried bind this in constructor, but it doesn't help. Can you help me fix this or give me a suggestion?
constructor() {
super();
this.state = {
list,
};
this.onDismiss = this.onDismiss.bind(this);
}
onDismiss(id) {
const isNotId = (item) => item.objectID !== id;
const updatedList = this.state.list.filter(isNotId);
this.setState({list : updatedList});
}
render() {
return (
<div className="App">
{this.state.list.map( item =>
<div key={item.objectID}>
<span>
<button onClick={ function() {this.onDismiss(item.objectID)}} type="button">
Dismiss
</button>
</span>
</div>
)}
</div>
);
}
}```
Solution 1:[1]
The problem is that here:
<button onClick={ function() {this.onDismiss(item.objectID)}} type="button">
Dismiss
</button>
Your inline function
is unbound, ending in this
being undefined. Replace it with an arrow function, and it will work:
<button onClick={() => this.onDismiss(item.objectID)} type="button">
Dismiss
</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | moonwave99 |