Zet
Zet

Reputation: 571

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?

Upvotes: 0

Views: 448

Answers (2)

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37594

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.

Upvotes: 3

Axnyff
Axnyff

Reputation: 9944

This does not work because in javascript this is dynamic. setInterval is actually window.setInterval so inside the function, this will be window. arrow functions are more than syntaxic sugar, they actually do not redefine this.

Upvotes: 0

Related Questions