Why is onClick invoked when rendering?

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 bound the function, but it is still called render. This is also how they do it in React docs: https://facebook.imtqy.com/react/docs/handling-events.html

This only works if I do it like this:

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

Then handleClick is called only when the button is clicked.

+4
source share
1 answer

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

Change it to

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

Source: https://habr.com/ru/post/1677340/


All Articles