Dan
Dan

Reputation: 11

Difference between function components and component classes?

This is following a tutorial in React JS.

  class Square extends React.Component {
    render() {
        return (
        <button
            className="square"
            onClick={() => this.props.onClick()}
        >
            {this.props.value}
        </button>
        );
    }
  }

   function Square(props) {
        return (
            <button className="square" onClick={props.onClick}>
            {props.value}
            </button>
        );
    }    

above components do the same thing.there's a statement in the tutorial as follows

"When we modified the Square to be a function component, we also changed onClick={() => this.props.onClick()} to a shorter onClick={props.onClick} (note the lack of parentheses on both sides)."

I don't understand why there aren't parentheses on the right side in the function component? is it not a function call?

Upvotes: 0

Views: 155

Answers (2)

Sagiv b.g
Sagiv b.g

Reputation: 31024

When passing a handler we actually need to pass a reference to a function.

I don't understand why there aren't parentheses on the right side in the function component? is it not a function call?

When you put parentheses you are invoking the function.
So when doing this:

onClick={props.onClick()}

We are passing the returned value of that function instead of a reference to it.

Upvotes: 0

Quentin
Quentin

Reputation: 943220

is it not a function call?

No, it isn't. It is a function. You are passing it to be the value of the onClick property.

This is a function that does nothing except call foo and return its value.

() => foo()

This is the function foo:

foo

The net result is more-or-less the same unless foo cares about the value of this or the arguments it gets.


If you added () to the short version, you would call the function immediately and pass the return value to onClick. Since that return value (probably) isn't a function, and you don't want the function to run until the click happens, that wouldn't be helpful.


function run_me(a_function) {
    a_function();
}

function foo() {
    console.log("foo has run");
}

run_me(foo);
run_me(() => foo());
run_me(foo());

Upvotes: 1

Related Questions