0

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

1
  • What would happen if you didn't change it? Commented Aug 12, 2019 at 13:38

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.