Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
Why is the this keyword inside clickHandler undefined?

I was following a YouTube tutorial on eventHandling when I got confused with the implementation of this keyword.

In the code below, the this keyword inside of clickHandler function gives the value of undefined. The instructor said that it is because that's how JavaScript works. But when I searched online I found out that this keyword when used inside a function of a class, points to the object itself.

This might be a stupid question to ask but since I am new to JavaScript any help will be appreciated

class EventBind extends Component {
  constructor(props) {
    super(props);

    this.state = {
      message: "Hello",
    };
  }

  clickHandler() {
    // this.setState({
    //   message : 'Goodbye'
    // })
    console.log(this);
  }

  render() {
    return (
      <div>
        <div>{this.state.message}</div>
        <button onClick = {this.clickHandler}>Click</button>
      </div>
    );
  }
}

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This is cause you have not bound the clickHandler to this. Try below code

class EventBind extends Component {
  constructor(props) {
    super(props);
    this.clickHandler = this.clickHandler.bind(this);
    ...

  }
  clickHandler() {
    ...
  }
  ...
  
}

See here for more info: https://reactjs.org/docs/faq-functions.html

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!