0

I have written a simple react code that just increases the value of 'numbers' when clicking on the button. It works well.

import React from "react";
import "./styles.css";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      numbers: 1
    };
  }

handleClick = () =>{
  this.setState({
    numbers: this.state.numbers+1
  })
}

  render() {
    return (
      <div className="App">
        <h1>Incrementer</h1>
        <input type="submit" name="submit" value="increment" onClick={this.handleClick}/>
        <br/>
        <h1>{this.state.numbers}</h1>
      </div>
    );
  }
}

I have a query regarding the line:

<input type="submit" name="submit" value="increment" onClick={this.handleClick}/>

When I change the above line as shown below, it still works:

<input type="submit" name="submit" value="increment" onClick={() => this.handleClick()}/>

But, if I change it to

onClick={this.handleClick()}

or

onClick={handleClick()}

or

onClick={function clickFunction(){this.handleClick()}}

it does not compile.

onClick={() => this.handleClick()}

I'm not able to understand the difference. Kindly help.

  • 3
    Think about the difference between `var result = someFunc` vs `var result = someFunc()` – Phil Aug 23 '21 at 06:57
  • 1
    You need to allow React to call the `handleClick` function when the `click` event is triggered which can be done by providing a function to `onClick={}`. This `onClick={this.handleClick()}` calls the function and the result of calling `this.handleClick` is passed to `onClick` – Yousaf Aug 23 '21 at 06:58
  • 1
    `onClick={this.handleClick}` assigns the function `handleClick` to the click event, same happens with `onClick={() => this.handleClick()}` But in `onClick={this.handleClick()}` its is calling the function `handleClick` directly while the template executes. If this function return something like a listner, that will be assigned to the click event. Or else the click event that you except to call on the click will be called directly on the template rendering – Nitheesh Aug 23 '21 at 07:01
  • Thank you @Phil @Yousaf and @Nitheesh I got it now. I have one more question. Aren't these two same? `onClick={() => this.handleClick()} ` and `onClick= {function x(){return this.handleClick()}}` Why does the second one doesn't work? – Gautham Muralidharan Aug 23 '21 at 07:27
  • @GauthamMuralidharan the second one doesn't work because you're using a regular `function()`, which has it's own `this` binding. With an arrow function the `this` that is used is taken from the surrounding scope (ie: your class) but with a regular function, the `this` is determined based on how that function is invoked (which is done for you by react), so the `this` won't be your component/class – Nick Parsons Aug 23 '21 at 23:53

0 Answers0