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

220
Views
What are the aspects of JS binding?

Have the following simpliest component.

class App extends Component {
  constructor(props) {
    super(props);
    console.log(this);
    this.state = {
      name: "John"
    }
  }

  clickHandler() {
    this.setState({
      name: "Mark"
    })
  };

  render() {
    return (
      <div className="App">
        {this.state.name}
        <button onClick={this.clickHandler.bind(this)}></button>
      </div>
    )
  };
}

export default App;

If I write that

<button onClick={this.clickHandler}></button>

it says that this in

this.setState({
      name: "Mark"
    })

is undefined. That row

<button onClick={console.log(this)}></button>

shows that this is App. So if this is App why clickHandler does not bind automatically to that object before the dot?

<button onClick={this.clickHandler}></button>

As far as I understand in "context.function" the context should be bound to the function. Or it only works for "context.function()"?

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

0

Or it only works for "context.function()"?

That's exactly right. It depends on where the function is invoked.

Doing

<button onClick={this.clickHandler}></button>

passes the clickHandler as a parameter. React's internals see something not completely dissimilar to:

function button({ onClick }) {
  // ...
  theActualDOMButtonElement.addEventListener('click', onClick);
}

or

function button({ onClick }) {
  // ...
  theActualDOMButtonElement.addEventListener('click', (e) => {
    const reactCreatedSyntheticEvent = retrieveSyntheticEvent(e);
    onClick(reactCreatedSyntheticEvent);
  });
}

You're passing the this.clickHandler as a parameter, not invoking it immediately - since it gets invoked later, and how it's invoked later determines the this, you can't just do onClick={this.clickHandler} without making sure the this is correct, such as invoking the function inline, or by using a class field, or by using a functional component.

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!