React why onClick property function triggers without click)

React why onClick property function triggers without click)


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) {'querylist.remove', id)
  renderQueriesItems () {
    return => {
      return (
        <tr key={item._id}>
            <a className='removeButton' onClick={this.removeQuery(item._id)} />
  render () {
    return (
        <table className='queries'>

P.S. if I change
onClick={this.removeQuery(item._id) to
onClick={() => {'querylist.remove', item._id) }}
everything woks fine


I already have found an answer on Stackoverflow:

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)}


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().

Difference in ReactJS onClick function binding