Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does bind(this) in constructor do in ReactJS

I am familiar with Javascript function bind. But I don't understand why in following React.js snippet is this bind again to this. Has is something common with constructor, because this in constructor can have different values depending on usage?

Thank you in advance for replies

class QuotesLibrary extends React.Component {
  constructor(props) {
    super(props);
    this.search = debounce(this.search.bind(this), 300);
  }
  search(searchTerm) {
    this.props.relay.setVariables({searchTerm});
  }
  render() {
    return (
      <div className="quotes-library">
        <SearchForm searchAction={this.search} />
        <div className="quotes-list">
          {this.props.library.quotesConnection.edges.map(edge =>
            <Quote key={edge.node.id} quote={edge.node} />
          )}
        </div>
      </div>
    )
  }
}
like image 673
Petr F. Avatar asked Nov 15 '25 01:11

Petr F.


1 Answers

What this.search.bind(this) does it that it is binding the key this inside to the function to the context of your React Component and what it basically means is that whenever you try to access a property of the React Component, you can access it like this.props since this will then refer to the React Component's context and not the function itself.

The significance of this.search before bind is that it is trying to access the function search which is in the context of the React Component and hence you are only binding it once and not twice.

I hope I was able to explain the situation properly

like image 96
Shubham Khatri Avatar answered Nov 17 '25 18:11

Shubham Khatri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!