Mano Mini
Mano Mini

Reputation: 613

React `onClick` change between Function and Class component

In offical react tutorial they first write class component:

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

and then make it a function component

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

Why is the onClick change necessary?

Thanks

Upvotes: 0

Views: 72

Answers (4)

Domino987
Domino987

Reputation: 8774

That change is not necessary but can be omitted in both cases.

You can write it in both examples like this:

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

or like this which is better for performance, because it does not create a new function on every render:

onClick={this.props.onClick}>

The only difference is, where the function is coming from. In the first case it comes from the this.props since it a class component and the props are not passed directly into the render function. In the function component, the props are directly passed into the function and can be accessed by props.onClick.

Upvotes: 0

Eric
Eric

Reputation: 603

In the function component, props are accessed through the parameter props directly (notice how it is passed in), as it's an object. In the class component, props exists on the class itself, and there is not variable named props.

Upvotes: 2

dance2die
dance2die

Reputation: 36895

Function Component receives a prop as a function argument (function Sqaure(props)),
while in Class Components, props are passed (or constructed from the constructor via super(props)) and made available via this.props.

Upvotes: 0

Quentin
Quentin

Reputation: 943214

props changed from being a property of the component object to being an argument passed to the function.

Upvotes: 0

Related Questions