Search This Blog

Thursday, September 17, 2020

the fat arrow magic in React

Well this confuses a lot of people when it comes to updating states in react 
components as well as referring to local variables or calling the main components functions.

To capture events from current components and pass the values to state
you can use the following.

passing input values via onchange handlers and to set them to state you can use fat arrow
i love fat arrow because you dont have to worry about this.value everywhere..

<input onChange = {()=> this.componentFuncttion(e)>

componentFunction = (e)=>this.setState({stateVariable:e.target.value});

Beauty here is this above refers to the main component this and the valuesis passed to the state..


Another beautiful use of fat arrow I have seen is that ... you don't need to pass variables inside the
function and you can directly refer to the variables which are above the scope of the fat arrow... 

but make sure if the structure is like below.. than fat arrow will refer to the closest _this and not the parent this.


CoolComponent extends React.component {

constructor(){

}
var a = 10;
function getData(a){

var a = 0 ;

const input = <input onChange={e=>this.a=1}/>
//now this refers to the closest a =0 which
}

console.log(' value of a is' + getData(a));// will print 1
console.log('value of a is + a) //will print 10 


}

No comments:

Post a Comment