5
import React, { Component } from 'react';

class Bookmark extends Component {
  constructor(props) {
    super(props);

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    console.log(this.props.idt);
  };

  render() {
    return (
      <div className='bookmark' onClick={this.handleClick()}/>
    );
  }
}
export default Bookmark;

This is my code. I've binded the function but it is still called on render. This is also how they do it in the React docs: https://facebook.github.io/react/docs/handling-events.html

It only works if I do it this way:

<div className='bookmark' onClick={() => this.handleClick()}/>

Then handleClick is called only when I click the button.

1
  • 1
    This will work as well.<div className='bookmark' onClick={this.handleClick}/> Commented May 17, 2017 at 10:10

1 Answer 1

8

Because you are passing a method call instead of the method itself.

Change it to

<div className='bookmark' onClick={this.handleClick}/>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Didnt even notice the ().
I am new to JS, so my question is: Why does the method call still get called? The onClick has not been triggered so the method call should not be called, correct?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.