Zet Zet - 1 year ago 165
React JSX Question

Equivalent of arrow function in react is not working

I have a component:

class ProbaShell extends React.Component{
constructor(props){
console.log('constructorStart');
super(props);

this.state = {
h: 5,
w: 500
};
this.fadeIn1 = this.fadeIn1.bind(this);
}


fadeIn1() {
const interval = setInterval(function(){
this.setState({ h: (this.state.h + 5) });
if (this.state.h >= 400) {
clearInterval(interval);
}
},50);
}

fadeIn() {
const interval = setInterval(() => {
this.setState({ h: (this.state.h + 5) });
if (this.state.h >= 400) {
clearInterval(interval);
}
}, 50);
}

render(){
console.log('render')
return(
<Proba style={{height: this.state.h}}/>
)
}

componentDidMount(){
console.log('compDidMount');
this.fadeIn();
}
}


and it is working perfectly with function fadeIn but not with fadeIn1. I cannot work out why? I've read an article about using this but still do not get why?

Answer Source

By using the fat arrow => it will auto bind it as a class method with the context. This does not happen for function(){..} so you have to bind it manually by doing

constructor(props){
    console.log('constructorStart');
    super(props);
    this.fadeIn1 = this.fadeIn1.bind(this);
}

and pass the context to the function e.g.

fadeIn1() {
    const interval = setInterval(function() {
        this.setState({
            h: (this.state.h + 5)
        });
        if (this.state.h >= 400) {
            clearInterval(interval);
        }
    }.bind(this), 50);
}

You can read more about Handling Events in React although this is more JavaScript specific.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download