1

I'm a beginner in ReactJS and JavaScript, and I'm trying to make a test class in ReactJS that every time the user clicks on the button, counts the click and display it on the tag of the buttton, If I use a normal function like this, it doesn't work:

class Button extends React.Component 
  {
   state = { counter : 0} 
   test = function ()
       {
         this.setState({    
                        counter : this.state.counter + 1
                      })
       }
  render(){
          return(<button onClick={this.test}>{this.state.counter}</button>)
          };
 }

But when I use Arrow Function on test , it works perfect :

   class Button extends React.Component 
          {  
           state = { counter : 0}
           test = () => {              ///////ONLY CHANGED THIS LINE    
           this.setState({      
               counter : this.state.counter + 1     
                        })
                        }
           render(){
           return(<button onClick={this.test}>{this.state.counter}</button>)
                   };
         }

Could anyone please explain me this behaviour ?

Nithin
  • 1,270
  • 10
  • 28
Diego
  • 184
  • 2
  • 16
  • https://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch – Aruna Herath Sep 19 '17 at 05:48
  • Check these answers for more details [When should I use Arrow functions in ECMAScript 6?](https://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6) and [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](https://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch) – Mayank Shukla Sep 19 '17 at 05:59

0 Answers0