Isa Kurehpaz
Isa Kurehpaz

Reputation: 57

Why is onClick being called on render?

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.

Upvotes: 5

Views: 1331

Answers (1)

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37624

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

Change it to

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

Upvotes: 8

Related Questions