Skip to content

Is it possible to remove the extra arrow function here? #3772

Description

@RuslanAsadov

Hi!
The tutorial has an example like this:

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

This component used in the Board component like this:

renderSquare(i) {
    return (
      <Square
        value={this.state.squares[i]}
        onClick={() => this.handleClick(i)}
      />
    );
  }

We have closed the context in a function that we pass to onClick in the Board component.
But why don't we just pass this.props.onClick to onClick in the Square component? Why are we using closures here if we already have the right context inside?

I wrote like this: (link to codepen)

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

This works successfully

It is clear that the variant from the tutorial will also work. But further it says:

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).

So my variation only works in a functional component? But above it also worked in class components. I think this might confuse some people.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions