React - Bind 'this' to a Class Method

Tell us what’s happening:
Describe your issue in detail here.

For the line of code: Click Me

I was wondering why we did not have to include the parentheses in {this.handleClick} like this: {this.handleClick()}. I thought the parentheses were necessary in order to call the function with onClick.
Your code so far

class MyComponent extends React.Component {
  constructor(props) {
    this.state = {
      text: "Hello"
    // Change code below this line
    this.handleClick = this.handleClick.bind(this); 
    // Change code above this line
  handleClick() {
      text: "You clicked!"
  render() {
    return (
        { /* Change code below this line */ }
        <button onClick={this.handleClick}>Click Me</button>
        { /* Change code above this line */ }

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36

Challenge: React - Bind ‘this’ to a Class Method

Link to the challenge:

If you added the parentheses, then the function would get called when the page loaded. You only supply the function to be called and React will handle calling what you specify in the onClick attribute.

In regular HTML, you might right onclick="functionName()", but JSX is not HTML. It is just special syntax that gets transpiled by something like Babel so JavaScript can use it.

1 Like

Thank you for your reply, it makes sense now!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.