Hello React experts and learners.
Here’s a react component. And one thing that I don’t understand is - why when this component renders, a click property function is being called.
class PreviousQuery extends Component {
...
removeQuery (id) {
Meteor.call('querylist.remove', id)
}
renderQueriesItems () {
return this.state.requests.map(item => {
return (
<tr key={item._id}>
<td>
<a className='removeButton' onClick={this.removeQuery(item._id)} />
</td>
</tr>
)
})
}
render () {
return (
<div>
<table className='queries'>
<tbody>
{this.renderQueriesItems()}
</tbody>
</table>
{console.log(this.state.requests)}
</div>
)
}
}
P.S. if I change
onClick={this.removeQuery(item._id)
to
onClick={() => { Meteor.call('querylist.remove', item._id) }}
everything woks fine
I already have found an answer on Stackoverflow:
http://stackoverflow.com/questions/32937365/button-onclick-triggered-when-init-in-react-application
When you use the onClick event and you want to pass parameters to the handler method, you have to use the function bind. Thus, the handler will be triggered only when you click on the list item.
onClick={this.handleClick.bind(this, argument)}
1 Like
Well you don’t have to use .bind().
All that does is create a new function with the this property set to whatever your first arguments is in the .bind() call.
The real issue was that your code which didn’t work wasn’t passing a function at all. It was passing the result of a call to your handler function. That’s why it looked like you were getting an event triggered - instead of passing a function, you were calling the handler function while creating the component.
In the code you posted which did work, it worked because you created a function (using arrow function syntax) which was passed in as the event handler function. When the event is triggered, that arrow function is called and inside of the arrow function the handler function you want is called.
This is largely the same as using .bind(). Unless your handler function needs ‘this’ as a specific object, there is no need to use .bind().
2 Likes