Search code examples
javascriptreactjsarrow-functions

onClick action not triggered using regular function in React


I am trying to render a series of buttons from an array of objects.

const numbers = 
[{
key:"C",
id:"clear"
},{
key:"/",
id:"divide"
},
{
key:"*",
id:"multiply"
}]

I tried to use regular function. It renders the buttons, but it wouldn't trigger the click action.

{numbers.map( function(item) {
          return (<button class="button btn btn-light" id={item.id} onClick={this.handleClick}>{item.key}</button>);
        }

The following works

  {numbers.map( item=>
               <button class="button btn btn-light" id={item.id} onClick={this.handleClick}>{item.key}</button>)
  }

What do I need to change in regular function to make it behave like arrow function?


Solution

  • The below one doesn’t work because this context won’t be available inside regular function. You need to bind it so that this will be available.

    Also class is reserved for declaring components in react so to add css class names to jsx elemebts you have to use className instead of class.

    Also when you render jsx elements inside loop you must add unique key to top most element

    Also make sure you bind handleClick in constructor if it is regular function in your code. If it is arrow function then no need to do manual binding

    Change

      {numbers.map( function(item) {
          return (<button class="button btn btn-light" id={item.id} onClick={this.handleClick}>{item.key}</button>);
        })
      }
    

    To

      {numbers.map(function(item) {
          return (<button key={item.id} className="button btn btn-light" id={item.id} onClick={this.handleClick}>{item.key}</button>);
        }.bind(this)
      )}
    

    The second one in your question works because it uses arrow function