1
class First extends React.Component{
    handleClick(){
        alert('handle click');
    } 

    render(){
        return <div>
            <button onClick={this.handleClick}>click</button>
        </div>;
    }
 }

in above example why we need to use this.handleClick instead of just handleclick

when this is not used

'handleClick' is not defined no-undef

an indepth explanation is appreciated

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Sanjay
  • 838
  • 1
  • 14
  • 21
  • You also need to add a binding: `... onClick={this.handleClick.bind(this)}`. Otherwise `this` value inside the `handleClick` method will have an unexpected value when you click the button. You can find more information about it here: https://reactjs.org/docs/handling-events.html – Finesse May 20 '18 at 09:15

2 Answers2

3

This isn't a React thing. It's a JavaScript thing.

Without this., handleClick is an identifier reference, and that means you have to have an in-scope declared variable with the name handleClick. You don't have that. You have a property on the component instance called handleClick, but that's not in scope anywhere.

It's the same reason you need this here:

class Example {
  constructor(value) {
    this.value = value;
  }
  
  showValue() {
    console.log(this.value); // <== Works
  }
  
  brokenShowValue() {
    console.log(value);      // <== ReferenceError, `value` is not defined
  }
}
const e = new Example(42);
e.showValue();
e.brokenShowValue();

There are languages which allow this. to be implicit (such as Java and C#), but JavaScript does not.


Side note: If at some point you use this in handleClick (you don't currently), be sure to read this question's answers. You'll need to do something to ensure that the correct this is available within the call (your code doesn't do that at the moment).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Because in JavaScript class properties and methods are not available directly by their name:

class Foo {
    bar() {}
    test() {
        bar(); // Error: undefined function
    }
}

When you call bar() in the example above, JavaScript tries to find the function called bar in the global namespace.

You need to type this. explicitly to access a current object property or method:

class Foo {
    bar() {}
    test() {
        this.bar(); // OK
    }
}
Finesse
  • 9,793
  • 7
  • 62
  • 92
  • can you give an example of function in global namespace as :-" JavaScript tries to find the function called bar in the global namespace." @Finesse – Sanjay May 20 '18 at 09:17
  • 1
    @SanjaySinghBhandari `function bar() { console.log(1) } class Foo { bar() { console.log(2) } test() { bar(/* logs "1" */); this.bar(/* logs "2" */); } }` – Finesse May 20 '18 at 09:19