Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 784
Isa Kurehpaz Avatar asked Mar 09 '23 01:03

Isa Kurehpaz


1 Answers

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

Change it to

<div className='bookmark' onClick={this.handleClick}/>
like image 61
Murat Karagöz Avatar answered Mar 19 '23 04:03

Murat Karagöz