loading...

3 Methods of binding in react

abodmicheal profile image Abod Micheal ・1 min read

This tutorial are for developers who already know React or beginners learning React,
Binding in React is used to pass a callback without worrying about it losing its context.
There are 3 ways to bind in react which are listed below
*) This method is the regular method where by we add our bind method inside of the constructor

class counter extends React.Component {
 constructor () {
  super() 
   this.state = {
     count: 0
   }
    this.incre = this.incre.bind(this)
 } 
 incre()  {
     this.setState({count: this.state.count +1})
}

} 

*) Adding your function inside of the Constructor , the normal way of binding is adding ///this.dataf= this.dataf.bind(this)///
but in this type we are adding the function inside of the constructor not the bind method .

class counter extends React.Component {
 constructor () {
  super() 
   this.state = {
     count: 0
   }
    this.incre = () => {
     this.setState({count: this.state.count +1})
}
 }

} 

*) This last method is a method I mostly use, all we do is do is use a nameless function or an arrow function . The nameless function would give it a lexical this inside which doesn't create it's own this context it inherit the class this.

class counter extends React.Component {
 constructor () {
  super() 
   this.state = {
     count: 0
   }
 } 
 incre = () => {
     this.setState({count: this.state.count +1})
}

} 

Posted on by:

Discussion

markdown guide