Functions as props

So this is what happens in this component:

click 1 - alert displays immediately and then button does nothing
click 2 - this is undefined
click 3 - on click alert displays
click 4 - on click alert displays

you can open it here: test-class - CodeSandbox

Correct me if I’m wrong:

  • this.handleClick() is invoked even before we bind this to handleClick2 and thats why click 2 displays error?
  • is there any difference between passing a regular and arrow function between components?
import React from "react";

class App extends React.Component {
  constructor() {
    super();
    this.name = "Message";

    this.handleClick2 = this.handleClick1.bind(this);
  }

  handleClick1() {
    alert(this.name);
  }

  handleClick3 = () => alert(this.name);
  render() {
    return (
      <div>
        <button onClick={this.handleClick1()}>click 1</button>
        <button onClick={this.handleClick1}>click 2</button>
        <button onClick={this.handleClick2}>click 3</button>
        <button onClick={this.handleClick3}>click 4</button>
      </div>
    );
  }
}

export default App;

handleClick refers to the value stored in “handleClick” variable, it could be function, string, whatever. handleClick() calls the function and returns its value(if any, not all function return as you know). When we bind a function to onClick, or other method attributes, we want to refer to that function, not execute it. We simply say, when the user clicks, use this function. Otherwise on click will execute the value returned by the function(if we were to write it as we call it) and if that value is not the handler, nothing will happen. I mean, you could technically do bind handleClick() on the onClick event, but it should return a handler function as a value, with which the on click would work with.
If you want to pass arguments to the handler function, a good practice is to use anonymous arrow functions to declare it inline, within the onClick assigment. For example onClick={()=>handleClick('some value')}. Notice how, i dont call handleClick, nore i call the arrow functions its part of. I only declare an arrow function, which will call handleClick with the given arguments, once the arrow function is called(which will happen on click).

This is the definition of a function:

function example () {
  console.log("example");
}

This is a reference to that function, ie the name under which you can look it up in memory:

example

This is the result of calling the function, ie what the return value is:

example()

This is also, in this case, exactly the same as example():

undefined

(This particular function returns nothing)

The onClick property is an event handler, it expects a function it can run. this.handleClick1() is not a function, it’s the return value of a function.